Browse Source

Remove Google URL shortener (fix #146) (#150)

pull/152/head
mutantmonkey 6 years ago
committed by Andrei Marcu
parent
commit
10938a3e0b
  1. 1
      README.md
  2. 1
      backends/meta.go
  3. 3
      backends/metajson/metajson.go
  4. 16
      display.go
  5. 8
      server.go
  6. 89
      shorturl.go
  7. 39
      static/js/shorturl.js
  8. 13
      templates/display/base.html

1
README.md

@ -54,7 +54,6 @@ allowhotlink = true
- ```-xframeoptions "..." ``` -- X-Frame-Options header (default is "SAMEORIGIN")
- ```-remoteuploads``` -- (optionally) enable remote uploads (/upload?url=https://...)
- ```-nologs``` -- (optionally) disable request logs in stdout
- ```-googleapikey``` -- (optionally) API Key for Google's URL Shortener. ([How to create one](https://developers.google.com/url-shortener/v1/getting_started#APIKey))
#### SSL with built-in server
- ```-certfile path/to/your.crt``` -- Path to the ssl certificate (required if you want to use the https server)

1
backends/meta.go

@ -17,7 +17,6 @@ type Metadata struct {
Size int64
Expiry time.Time
ArchiveFiles []string
ShortURL string
}
var BadMetadata = errors.New("Corrupted metadata.")

3
backends/metajson/metajson.go

@ -15,7 +15,6 @@ type MetadataJSON struct {
Size int64 `json:"size"`
Expiry int64 `json:"expiry"`
ArchiveFiles []string `json:"archive_files,omitempty"`
ShortURL string `json:"short_url"`
}
type MetaJSONBackend struct {
@ -30,7 +29,6 @@ func (m MetaJSONBackend) Put(key string, metadata *backends.Metadata) error {
mjson.Sha256sum = metadata.Sha256sum
mjson.Expiry = metadata.Expiry.Unix()
mjson.Size = metadata.Size
mjson.ShortURL = metadata.ShortURL
byt, err := json.Marshal(mjson)
if err != nil {
@ -63,7 +61,6 @@ func (m MetaJSONBackend) Get(key string) (metadata backends.Metadata, err error)
metadata.Sha256sum = mjson.Sha256sum
metadata.Expiry = time.Unix(mjson.Expiry, 0)
metadata.Size = mjson.Size
metadata.ShortURL = mjson.ShortURL
return
}

16
display.go

@ -116,15 +116,13 @@ func fileDisplayHandler(c web.C, w http.ResponseWriter, r *http.Request) {
}
err = renderTemplate(tpl, pongo2.Context{
"mime": metadata.Mimetype,
"filename": fileName,
"size": sizeHuman,
"expiry": expiryHuman,
"extra": extra,
"lines": lines,
"files": metadata.ArchiveFiles,
"shorturlEnabled": Config.googleShorterAPIKey != "",
"shorturl": metadata.ShortURL,
"mime": metadata.Mimetype,
"filename": fileName,
"size": sizeHuman,
"expiry": expiryHuman,
"extra": extra,
"lines": lines,
"files": metadata.ArchiveFiles,
}, r, w)
if err != nil {

8
server.go

@ -59,7 +59,6 @@ var Config struct {
authFile string
remoteAuthFile string
addHeaders headerList
googleShorterAPIKey string
noDirectAgents bool
}
@ -154,7 +153,6 @@ func setup() *web.Mux {
selifRe := regexp.MustCompile("^" + Config.sitePath + `selif/(?P<name>[a-z0-9-\.]+)$`)
selifIndexRe := regexp.MustCompile("^" + Config.sitePath + `selif/$`)
torrentRe := regexp.MustCompile("^" + Config.sitePath + `(?P<name>[a-z0-9-\.]+)/torrent$`)
shortRe := regexp.MustCompile("^" + Config.sitePath + `(?P<name>[a-z0-9-\.]+)/short$`)
if Config.authFile == "" {
mux.Get(Config.sitePath, indexHandler)
@ -193,10 +191,6 @@ func setup() *web.Mux {
mux.Get(selifIndexRe, unauthorizedHandler)
mux.Get(torrentRe, fileTorrentHandler)
if Config.googleShorterAPIKey != "" {
mux.Get(shortRe, shortURLHandler)
}
mux.NotFound(notFoundHandler)
return mux
@ -251,8 +245,6 @@ func main() {
"value of X-Frame-Options header")
flag.Var(&Config.addHeaders, "addheader",
"Add an arbitrary header to the response. This option can be used multiple times.")
flag.StringVar(&Config.googleShorterAPIKey, "googleapikey", "",
"API Key for Google's URL Shortener.")
flag.BoolVar(&Config.noDirectAgents, "nodirectagents", false,
"disable serving files directly for wget/curl user agents")

89
shorturl.go

@ -1,89 +0,0 @@
package main
import (
"bytes"
"encoding/json"
"errors"
"net/http"
"github.com/zenazn/goji/web"
)
type shortenerRequest struct {
LongURL string `json:"longUrl"`
}
type shortenerResponse struct {
Kind string `json:"kind"`
ID string `json:"id"`
LongURL string `json:"longUrl"`
Error struct {
Code int `json:"code"`
Message string `json:"message"`
} `json:"error"`
}
func shortURLHandler(c web.C, w http.ResponseWriter, r *http.Request) {
fileName := c.URLParams["name"]
err := checkFile(fileName)
if err == NotFoundErr {
notFoundHandler(c, w, r)
return
}
metadata, err := metadataRead(fileName)
if err != nil {
oopsHandler(c, w, r, RespJSON, "Corrupt metadata.")
return
}
if metadata.ShortURL == "" {
url, err := shortenURL(getSiteURL(r) + fileName)
if err != nil {
oopsHandler(c, w, r, RespJSON, err.Error())
return
}
metadata.ShortURL = url
err = metadataWrite(fileName, &metadata)
if err != nil {
oopsHandler(c, w, r, RespJSON, "Corrupt metadata.")
return
}
}
js, _ := json.Marshal(map[string]string{
"shortUrl": metadata.ShortURL,
})
w.Write(js)
return
}
func shortenURL(url string) (string, error) {
apiURL := "https://www.googleapis.com/urlshortener/v1/url?key=" + Config.googleShorterAPIKey
jsonStr, _ := json.Marshal(shortenerRequest{LongURL: url})
req, err := http.NewRequest("POST", apiURL, bytes.NewBuffer(jsonStr))
req.Header.Set("Content-Type", "application/json")
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return "", err
}
defer resp.Body.Close()
shortenerResponse := new(shortenerResponse)
err = json.NewDecoder(resp.Body).Decode(shortenerResponse)
if err != nil {
return "", err
}
if shortenerResponse.Error.Message != "" {
return "", errors.New(shortenerResponse.Error.Message)
}
return shortenerResponse.ID, nil
}

39
static/js/shorturl.js

@ -1,39 +0,0 @@
document.getElementById('shorturl').addEventListener('click', function (e) {
e.preventDefault();
if (e.target.href !== "") return;
xhr = new XMLHttpRequest();
xhr.open("GET", e.target.dataset.url, true);
xhr.setRequestHeader('Accept', 'application/json');
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
var resp = JSON.parse(xhr.responseText);
if (xhr.status === 200 && resp.error == null) {
e.target.innerText = resp.shortUrl;
e.target.href = resp.shortUrl;
e.target.setAttribute('aria-label', 'Click to copy into clipboard')
} else {
e.target.setAttribute('aria-label', resp.error)
}
}
};
xhr.send();
});
var clipboard = new Clipboard("#shorturl", {
text: function (trigger) {
if (trigger.href == null) return;
return trigger.href;
}
});
clipboard.on('success', function (e) {
e.trigger.setAttribute('aria-label', 'Successfully copied')
});
clipboard.on('error', function (e) {
e.trigger.setAttribute('aria-label', 'Your browser does not support coping to clipboard')
});

13
templates/display/base.html

@ -17,15 +17,6 @@
{% endif %}
{% block infomore %}{% endblock %}
<span>{{ size }}</span> |
{% if shorturlEnabled %}
{% if shorturl %}
<a class="hint--top" aria-label="Click to copy into clipboard" id="shorturl"
style="cursor: pointer;" href="{{shorturl}}">{{shorturl}}</a> |
{% else %}
<a class="hint--top" aria-label="Click to retrieve shortened url" id="shorturl"
data-url="{{ sitepath }}{{filename}}/short" style="cursor: pointer;">short url</a> |
{% endif %}
{% endif %}
<a href="{{ filename }}/torrent" download>torrent</a> |
<a href="{{ sitepath }}selif/{{ filename }}" download>get</a>
</div>
@ -43,8 +34,4 @@
</div>
<script src="{{ sitepath }}static/js/clipboard.js"></script>
{% if shorturlEnabled %}
<script src="{{ sitepath }}static/js/shorturl.js"></script>
{% endif %}
{% endblock %}
Loading…
Cancel
Save