You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

288 lines
11 KiB

8 years ago
8 years ago
8 years ago
  1. // Package imgur implements a Service which adds !commands for imgur image search
  2. package imgur
  3. import (
  4. "encoding/json"
  5. "fmt"
  6. "io/ioutil"
  7. "math/rand"
  8. "net/http"
  9. "net/url"
  10. "strings"
  11. "github.com/matrix-org/go-neb/types"
  12. "github.com/matrix-org/gomatrix"
  13. log "github.com/sirupsen/logrus"
  14. )
  15. // ServiceType of the Imgur service
  16. const ServiceType = "imgur"
  17. var httpClient = &http.Client{}
  18. // Represents an Imgur Gallery Image
  19. type imgurGalleryImage struct {
  20. ID string `json:"id"` // The ID for the image
  21. Title string `json:"title"` // The title of the image.
  22. Description string `json:"description"` // Description of the image.
  23. DateTime int64 `json:"datetime"` // Time inserted into the gallery, epoch time
  24. Type string `json:"type"` // Image MIME type.
  25. Animated *bool `json:"animated"` // Is the image animated
  26. Width int `json:"width"` // The width of the image in pixels
  27. Height int `json:"height"` // The height of the image in pixels
  28. Size int64 `json:"size"` // The size of the image in bytes
  29. Views int64 `json:"views"` // The number of image views
  30. Link string `json:"link"` // The direct link to the the image. (Note: if fetching an animated GIF that was over 20MB in original size, a .gif thumbnail will be returned)
  31. Gifv string `json:"gifv"` // OPTIONAL, The .gifv link. Only available if the image is animated and type is 'image/gif'.
  32. MP4 string `json:"mp4"` // OPTIONAL, The direct link to the .mp4. Only available if the image is animated and type is 'image/gif'.
  33. MP4Size int64 `json:"mp4_size"` // OPTIONAL, The Content-Length of the .mp4. Only available if the image is animated and type is 'image/gif'. Note that a zero value (0) is possible if the video has not yet been generated
  34. Looping *bool `json:"looping"` // OPTIONAL, Whether the image has a looping animation. Only available if the image is animated and type is 'image/gif'.
  35. NSFW *bool `json:"nsfw"` // Indicates if the image has been marked as nsfw or not. Defaults to null if information is not available.
  36. Topic string `json:"topic"` // Topic of the gallery image.
  37. Section string `json:"section"` // If the image has been categorized by our backend then this will contain the section the image belongs in. (funny, cats, adviceanimals, wtf, etc)
  38. IsAlbum *bool `json:"is_album"` // If it's an album or not
  39. // ** Unimplemented fields **
  40. // bandwidth integer Bandwidth consumed by the image in bytes
  41. // deletehash string OPTIONAL, the deletehash, if you're logged in as the image owner
  42. // comment_count int Number of comments on the gallery image.
  43. // topic_id integer Topic ID of the gallery image.
  44. // vote string The current user's vote on the album. null if not signed in or if the user hasn't voted on it.
  45. // favorite boolean Indicates if the current user favorited the image. Defaults to false if not signed in.
  46. // account_url string The username of the account that uploaded it, or null.
  47. // account_id integer The account ID of the account that uploaded it, or null.
  48. // ups integer Upvotes for the image
  49. // downs integer Number of downvotes for the image
  50. // points integer Upvotes minus downvotes
  51. // score integer Imgur popularity score
  52. }
  53. // Represents an Imgur gallery album
  54. type imgurGalleryAlbum struct {
  55. ID string `json:"id"` // The ID for the album
  56. Title string `json:"title"` // The title of the album.
  57. Description string `json:"description"` // Description of the album.
  58. DateTime int64 `json:"datetime"` // Time inserted into the gallery, epoch time
  59. Views int64 `json:"views"` // The number of album views
  60. Link string `json:"link"` // The URL link to the album
  61. NSFW *bool `json:"nsfw"` // Indicates if the album has been marked as nsfw or not. Defaults to null if information is not available.
  62. Topic string `json:"topic"` // Topic of the gallery album.
  63. IsAlbum *bool `json:"is_album"` // If it's an album or not
  64. Cover string `json:"cover"` // The ID of the album cover image
  65. CoverWidth int `json:"cover_width"` // The width, in pixels, of the album cover image
  66. CoverHeight int `json:"cover_height"` // The height, in pixels, of the album cover image
  67. ImagesCount int `json:"images_count"` // The total number of images in the album
  68. Images []imgurGalleryImage `json:"images"` // An array of all the images in the album (only available when requesting the direct album)
  69. // ** Unimplemented fields **
  70. // account_url string The account username or null if it's anonymous.
  71. // account_id integer The account ID of the account that uploaded it, or null.
  72. // privacy string The privacy level of the album, you can only view public if not logged in as album owner
  73. // layout string The view layout of the album.
  74. // views integer The number of image views
  75. // ups integer Upvotes for the image
  76. // downs integer Number of downvotes for the image
  77. // points integer Upvotes minus downvotes
  78. // score integer Imgur popularity score
  79. // vote string The current user's vote on the album. null if not signed in or if the user hasn't voted on it.
  80. // favorite boolean Indicates if the current user favorited the album. Defaults to false if not signed in.
  81. // comment_count int Number of comments on the gallery album.
  82. // topic_id integer Topic ID of the gallery album.
  83. }
  84. // Imgur gallery search response
  85. type imgurSearchResponse struct {
  86. Data []json.RawMessage `json:"data"` // Data temporarily stored as RawMessage objects, as it can contain a mix of imgurGalleryImage and imgurGalleryAlbum objects
  87. Success *bool `json:"success"` // Request completed successfully
  88. Status int `json:"status"` // HTTP response code
  89. }
  90. // Service contains the Config fields for the Imgur service.
  91. //
  92. // Example request:
  93. // {
  94. // "client_id": "AIzaSyA4FD39..."
  95. // "client_secret": "ASdsaijwdfASD..."
  96. // }
  97. type Service struct {
  98. types.DefaultService
  99. // The Imgur client ID
  100. ClientID string `json:"client_id"`
  101. // The API key to use when making HTTP requests to Imgur.
  102. ClientSecret string `json:"client_secret"`
  103. }
  104. // Commands supported:
  105. // !imgur some_search_query_without_quotes
  106. // Responds with a suitable image into the same room as the command.
  107. func (s *Service) Commands(client *gomatrix.Client) []types.Command {
  108. return []types.Command{
  109. types.Command{
  110. Path: []string{"imgur", "help"},
  111. Command: func(roomID, userID string, args []string) (interface{}, error) {
  112. return usageMessage(), nil
  113. },
  114. },
  115. types.Command{
  116. Path: []string{"imgur"},
  117. Command: func(roomID, userID string, args []string) (interface{}, error) {
  118. return s.cmdImgSearch(client, roomID, userID, args)
  119. },
  120. },
  121. }
  122. }
  123. // usageMessage returns a matrix TextMessage representation of the service usage
  124. func usageMessage() *gomatrix.TextMessage {
  125. return &gomatrix.TextMessage{"m.notice",
  126. `Usage: !imgur image_search_text`}
  127. }
  128. // Search Imgur for a relevant image and upload it to matrix
  129. func (s *Service) cmdImgSearch(client *gomatrix.Client, roomID, userID string, args []string) (interface{}, error) {
  130. // Check for query text
  131. if len(args) < 1 {
  132. return usageMessage(), nil
  133. }
  134. // Perform search
  135. querySentence := strings.Join(args, " ")
  136. searchResultImage, searchResultAlbum, err := s.text2img(querySentence)
  137. if err != nil {
  138. return nil, err
  139. }
  140. // Image returned
  141. if searchResultImage != nil {
  142. var imgURL = searchResultImage.Link
  143. if imgURL == "" {
  144. return gomatrix.TextMessage{
  145. MsgType: "m.notice",
  146. Body: "No image found!",
  147. }, nil
  148. }
  149. // Upload image
  150. resUpload, err := client.UploadLink(imgURL)
  151. if err != nil {
  152. return nil, fmt.Errorf("Failed to upload Imgur image (%s) to matrix: %s", imgURL, err.Error())
  153. }
  154. // Return image message
  155. return gomatrix.ImageMessage{
  156. MsgType: "m.image",
  157. Body: querySentence,
  158. URL: resUpload.ContentURI,
  159. Info: gomatrix.ImageInfo{
  160. Height: uint(searchResultImage.Height),
  161. Width: uint(searchResultImage.Width),
  162. Mimetype: searchResultImage.Type,
  163. },
  164. }, nil
  165. } else if searchResultAlbum != nil {
  166. return gomatrix.TextMessage{
  167. MsgType: "m.notice",
  168. Body: "Search returned an album - Not currently supported",
  169. }, nil
  170. } else {
  171. return gomatrix.TextMessage{
  172. MsgType: "m.notice",
  173. Body: "No image found!",
  174. }, nil
  175. }
  176. }
  177. // text2img returns info about an image or an album
  178. func (s *Service) text2img(query string) (*imgurGalleryImage, *imgurGalleryAlbum, error) {
  179. log.Info("Searching Imgur for an image of a ", query)
  180. bytes, err := queryImgur(query, s.ClientID)
  181. if err != nil {
  182. return nil, nil, err
  183. }
  184. var searchResults imgurSearchResponse
  185. // if err := json.NewDecoder(res.Body).Decode(&searchResults); err != nil {
  186. if err := json.Unmarshal(bytes, &searchResults); err != nil {
  187. return nil, nil, fmt.Errorf("No images found - %s", err.Error())
  188. } else if len(searchResults.Data) < 1 {
  189. return nil, nil, fmt.Errorf("No images found")
  190. }
  191. log.Printf("%d results were returned from Imgur", len(searchResults.Data))
  192. // Return a random image result
  193. var images []imgurGalleryImage
  194. for i := 0; i < len(searchResults.Data); i++ {
  195. var image imgurGalleryImage
  196. if err := json.Unmarshal(searchResults.Data[i], &image); err == nil && !*(image.IsAlbum) {
  197. images = append(images, image)
  198. }
  199. }
  200. if len(images) > 0 {
  201. var r = 0
  202. if len(images) > 1 {
  203. r = rand.Intn(len(images) - 1)
  204. }
  205. return &images[r], nil, nil
  206. }
  207. return nil, nil, fmt.Errorf("No images found")
  208. }
  209. // Query imgur and return HTTP response or error
  210. func queryImgur(query, clientID string) ([]byte, error) {
  211. query = url.QueryEscape(query)
  212. // Build the query URL
  213. var sort = "time" // time | viral | top
  214. var window = "all" // day | week | month | year | all
  215. var page = 1
  216. var urlString = fmt.Sprintf("https://api.imgur.com/3/gallery/search/%s/%s/%d?q=%s", sort, window, page, query)
  217. u, err := url.Parse(urlString)
  218. if err != nil {
  219. return nil, err
  220. }
  221. req, err := http.NewRequest("GET", u.String(), nil)
  222. if err != nil {
  223. return nil, err
  224. }
  225. // Add authorisation header
  226. req.Header.Add("Authorization", "Client-ID "+clientID)
  227. res, err := httpClient.Do(req)
  228. if res != nil {
  229. defer res.Body.Close()
  230. }
  231. if err != nil {
  232. return nil, err
  233. }
  234. if res.StatusCode < 200 || res.StatusCode >= 300 {
  235. return nil, fmt.Errorf("Request error: %d, %s", res.StatusCode, response2String(res))
  236. }
  237. // Read and return response body
  238. bytes, err := ioutil.ReadAll(res.Body)
  239. if err != nil {
  240. return nil, err
  241. }
  242. return bytes, nil
  243. }
  244. // response2String returns a string representation of an HTTP response body
  245. func response2String(res *http.Response) string {
  246. bs, err := ioutil.ReadAll(res.Body)
  247. if err != nil {
  248. return "Failed to decode response body"
  249. }
  250. str := string(bs)
  251. return str
  252. }
  253. // Initialise the service
  254. func init() {
  255. types.RegisterService(func(serviceID, serviceUserID, webhookEndpointURL string) types.Service {
  256. return &Service{
  257. DefaultService: types.NewDefaultService(serviceID, serviceUserID, ServiceType),
  258. }
  259. })
  260. }