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.

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