summaryrefslogtreecommitdiff
path: root/earthporn.go
blob: 8267bc8b23e6f1953b8bc01f3e5bfded20ef3cb6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
package main

import (
	"bytes"
	"encoding/json"
	"errors"
	"fmt"
	"io"
	"log"
	"mime"
	"net/http"
	"os"
	"path"
	"strings"
)

type redditList struct {
	Data struct {
		Children []struct {
			Data *EarthPorn `json:"data"`
		} `json:"children"`
	} `json:"data"`
}

type EarthPorn struct {
	Title     string `json:"title"`
	URL       string `json:"url,omitempty"`
	Permalink string `json:"permalink"`
	Domain    string `json:"domain"`
	Saved     bool
	data      []byte
	mediatype string
}

const earthPornURL = "http://www.reddit.com/r/EarthPorn.json"

func GetEarthPorn() (EarthPorn, error) {
	resp, err := http.Get(earthPornURL)
	if err != nil {
		return EarthPorn{}, err
	}
	defer resp.Body.Close()

	var list redditList
	dec := json.NewDecoder(resp.Body)
	if err := dec.Decode(&list); err != nil {
		return EarthPorn{}, err
	}

	for _, el := range list.Data.Children {
		p := el.Data

		if p.Domain == "self.EarthPorn" {
			continue
		}

		if p.URL == "" {
			continue
		}

		if p.fetch() {
			return *p, nil
		}
	}

	return EarthPorn{}, errors.New("Could not get EarthPorn: No image could be extracted")
}

func (p *EarthPorn) fetch() bool {
	// TODO: We can do further processing here (e.g. if we get a link to flickr, extract the image).
	// For now, we will simply test, if the URL points to an image.

	resp, err := http.Get(p.URL)
	if err != nil {
		return false
	}
	defer resp.Body.Close()

	t := resp.Header.Get("Content-Type")
	if t == "" {
		log.Printf("could not get image of %s: no Content-Type", p.Permalink)
		return false
	}
	mt, _, err := mime.ParseMediaType(t)
	if err != nil {
		log.Printf("could not get image of %s: %s", p.Permalink, err)
		return false
	}

	if strings.Split(mt, "/")[0] != "image" {
		log.Printf("could not get image of %s: not an image", p.Permalink)
		return false
	}

	buf := new(bytes.Buffer)
	if _, err := io.Copy(buf, resp.Body); err != nil {
		log.Printf("could not get image of %s: %s", p.Permalink, err)
		return false
	}

	p.mediatype = t
	p.data = buf.Bytes()
	return true
}

var extensions = map[string]string{
	"image/png":      "png",
	"image/jpeg":     "jpg",
	"image/gif":      "gif",
	"image/x-ms-bmp": "bmp",
	"image/x-bmp":    "bmp",
	"image/bmp":      "bmp",
	"image/tiff":     "tiff",
	"image/tiff-fx":  "tiff",
	"image/x-targa":  "tga",
	"image/x-tga":    "tga",
	"image/webp":     "webp",
}

var savepath = ""

func setSavepathCmd(params []string) error {
	if len(params) != 1 {
		return errors.New("set-earthporn-savepath needs one parameter")
	}

	savepath = params[0]
	return nil
}

const maxTitleLenInFilename = 100

func (p *EarthPorn) save() error {
	ext := extensions[p.mediatype]
	pp := strings.Split(p.Permalink, "/")
	threadid := pp[len(pp)-3]

	title := strings.Replace(p.Title, "/", "-", -1)
	tRunes := []rune(title)
	if len(tRunes) > maxTitleLenInFilename {
		title = string(tRunes[0:maxTitleLenInFilename])
	}

	f, err := os.Create(path.Join(savepath, threadid+" - "+title+"."+ext))
	if err != nil {
		return fmt.Errorf("Could not save earthporn: %s", err)
	}
	defer f.Close()

	if _, err := f.Write(p.data); err != nil {
		return fmt.Errorf("Could not save earthporn: %s", err)
	}

	p.Saved = true

	return nil
}