Exemple #1
0
// GetConfig is a helper function for getting the current config
// from the request context.
func GetConfig(c context.Context) Config {
	if val, ok := c.GetGlobal(context.BaseCtxKey("config")); ok {
		return val.(Config)
	}

	return Config{}
}
Exemple #2
0
func (con Component) Handler(c context.Context) http.Handler {
	mw, i18nFound := con.dispatcher.Middleware("I18N")
	logger := webfw.GetLogger(c)

	rnd := renderer.NewRenderer(con.dispatcher.Config.Renderer.Dir, "raw.tmpl")
	rnd.Delims("{%", "%}")

	if i18nFound {
		if i18n, ok := mw.(middleware.I18N); ok {
			rnd.Funcs(i18n.TemplateFuncMap())
		}
	} else {
		logger.Infoln("I18N middleware not found")
	}

	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		params := webfw.GetParams(c, r)

		err := rnd.Render(w, renderer.RenderData{"apiPattern": con.apiPattern},
			c.GetAll(r), "components/"+params["name"]+".tmpl")

		if err != nil {
			webfw.GetLogger(c).Print(err)
		}
	})
}
Exemple #3
0
// GetParams returns the current request path parameters from the context.
func GetParams(c context.Context, r *http.Request) RouteParams {
	if val, ok := c.Get(r, context.BaseCtxKey("params")); ok {
		return val.(RouteParams)
	}

	return RouteParams{}
}
Exemple #4
0
func GetConfig(c context.Context) Config {
	if v, ok := c.GetGlobal(CtxKey("config")); ok {
		return v.(Config)
	}

	return Config{}
}
Exemple #5
0
// GetLanguage returns the current request language, such as "en", or "bg-BG"
// from the context, if the I18N middleware is in use.
func GetLanguage(c context.Context, r *http.Request) string {
	if val, ok := c.Get(r, context.BaseCtxKey("lang")); ok {
		return val.(string)
	}

	return GetFallbackLanguage(c, r)
}
Exemple #6
0
func GetRepo(c context.Context) content.Repo {
	if v, ok := c.GetGlobal(CtxKey("repo")); ok {
		return v.(content.Repo)
	}

	return nil
}
Exemple #7
0
// GetRenderCtx returns a RenderCtx wrapper around the current raw renderer
// The wrapper automatically adds the current request ContextData to the
// renderer's Render method call.
func GetRenderCtx(c context.Context, r *http.Request) renderer.RenderCtx {
	rnd := GetRenderer(c)

	return renderer.RenderCtx(func(w io.Writer, data renderer.RenderData, names ...string) error {
		return rnd.Render(w, data, c.GetAll(r), names...)
	})
}
Exemple #8
0
func (con App) Handler(c context.Context) http.Handler {
	cfg := readeef.GetConfig(c)
	rnd := webfw.GetRenderer(c)

	if cfg.Logger.Level == "debug" {
		rnd.SkipCache(true)
	}

	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		action := webfw.GetMultiPatternIdentifier(c, r)

		data := renderer.RenderData{}
		if action == "history" {
			params := webfw.GetParams(c, r)
			data["history"] = "/web/" + params["history"]
		}

		if r.Method != "HEAD" {
			err := rnd.Render(w, data, c.GetAll(r), "app.tmpl")
			if err != nil {
				webfw.GetLogger(c).Print(err)
			}
		}

		w.Header().Set("X-Readeef", "1")
	})
}
Exemple #9
0
func GetUser(c context.Context, r *http.Request) content.User {
	if v, ok := c.Get(r, context.BaseCtxKey("user")); ok {
		return v.(content.User)
	}

	return nil
}
Exemple #10
0
// GetLogger returns the error logger, to be used if an error occurs during
// a request.
func GetLogger(c context.Context) Logger {
	if val, ok := c.GetGlobal(context.BaseCtxKey("logger")); ok {
		return val.(Logger)
	}

	return NewStandardLogger(os.Stderr, "", 0)
}
Exemple #11
0
// GetRenderer returns the current raw renderer from the context.
func GetRenderer(c context.Context) renderer.Renderer {
	if val, ok := c.GetGlobal(context.BaseCtxKey("renderer")); ok {
		return val.(renderer.Renderer)
	}

	return renderer.NewRenderer("template", "base.tmpl")
}
Exemple #12
0
func forbidden(c context.Context, r *http.Request) bool {
	if v, ok := c.Get(r, readeef.CtxKey("forbidden")); ok {
		if f, ok := v.(bool); ok {
			return f
		}
	}

	return false
}
Exemple #13
0
func (con App) Handler(c context.Context) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		rnd := webfw.GetRenderer(c)

		err := rnd.Render(w, nil, c.GetAll(r), "app.tmpl")
		if err != nil {
			webfw.GetLogger(c).Print(err)
		}
	}
}
Exemple #14
0
func (con Component) Handler(c context.Context) http.HandlerFunc {
	rnd := renderer.NewRenderer(con.dir, "raw.tmpl")
	rnd.Delims("{%", "%}")

	return func(w http.ResponseWriter, r *http.Request) {
		params := webfw.GetParams(c, r)

		err := rnd.Render(w, renderer.RenderData{"apiPattern": con.apiPattern},
			c.GetAll(r), "components/"+params["name"]+".tmpl")

		if err != nil {
			webfw.GetLogger(c).Print(err)
		}
	}
}
Exemple #15
0
func GetDB(c context.Context) DB {
	if v, ok := c.GetGlobal(CtxKey("db")); ok {
		return v.(DB)
	}

	conf := GetConfig(c)

	db := NewDB(conf.DB.Driver, conf.DB.Connect)

	if err := db.Connect(); err != nil {
		panic(err)
	}

	return db
}
Exemple #16
0
func (con App) Handler(c context.Context) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		rnd := webfw.GetRenderer(c)
		action := webfw.GetMultiPatternIdentifier(c, r)

		data := renderer.RenderData{}
		if action == "history" {
			params := webfw.GetParams(c, r)
			data["history"] = "/web/" + params["history"]
		}

		err := rnd.Render(w, data, c.GetAll(r), "app.tmpl")
		if err != nil {
			webfw.GetLogger(c).Print(err)
		}
	})
}
Exemple #17
0
// The URL function provides the functionality of the url template functions
// for use outside of the template context. The dispatcherPattern is the
// pattern used by the dispatcher responsible for handling the resulting url.
// In most cases it will probably be "/".
func URL(c context.Context, r *http.Request, dispatcherPattern string, parts []string) (string, error) {
	base, err := unlocalizedUrl(r, parts)

	if err != nil {
		return "", err
	}

	if lang, ok := c.Get(r, context.BaseCtxKey("lang")); ok && len(lang.(string)) > 0 {
		base = "/" + lang.(string) + base
	}
	if len(dispatcherPattern) > 1 {
		base = dispatcherPattern[:len(dispatcherPattern)-1] + base
	}

	if len(base) > 1 && base[len(base)-1] == '/' {
		base = base[:len(base)-1]
	}
	return base, nil
}
Exemple #18
0
func (con Component) Handler(c context.Context) http.Handler {
	i18nmw, i18nFound := con.dispatcher.Middleware("I18N")
	urlmw, urlFound := con.dispatcher.Middleware("Url")
	logger := webfw.GetLogger(c)
	cfg := readeef.GetConfig(c)

	rnd := renderer.NewRenderer(con.dispatcher.Config.Renderer.Dir, "raw.tmpl")
	rnd.Delims("{%", "%}")

	if cfg.Logger.Level == "debug" {
		rnd.SkipCache(true)
	}

	if i18nFound {
		if i18n, ok := i18nmw.(middleware.I18N); ok {
			rnd.Funcs(i18n.TemplateFuncMap())
		}
	} else {
		logger.Infoln("I18N middleware not found")
	}

	if urlFound {
		if url, ok := urlmw.(middleware.Url); ok {
			rnd.Funcs(url.TemplateFuncMap(c))
		}
	} else {
		logger.Infoln("Url middleware not found")
	}

	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		params := webfw.GetParams(c, r)

		if r.Method != "HEAD" {
			err := rnd.Render(w, renderer.RenderData{"apiPattern": con.apiPattern, "config": cfg},
				c.GetAll(r), "components/"+params["name"]+".tmpl")

			if err != nil {
				webfw.GetLogger(c).Print(err)
			}
		}
	})
}
Exemple #19
0
// GetSession returns the current session from the context,
// if the Session middleware is in use.
func GetSession(c context.Context, r *http.Request) context.Session {
	if val, ok := c.Get(r, context.BaseCtxKey("session")); ok {
		return val.(context.Session)
	}

	conf := GetConfig(c)
	var abspath string

	if filepath.IsAbs(conf.Session.Dir) {
		abspath = conf.Session.Dir
	} else {
		var err error
		abspath, err = filepath.Abs(path.Join(filepath.Dir(os.Args[0]), conf.Session.Dir))

		if err != nil {
			abspath = os.TempDir()
		}
	}

	sess := context.NewSession([]byte(conf.Session.Secret), []byte(conf.Session.Cipher), abspath)
	sess.SetName(util.UUID())
	return sess
}
Exemple #20
0
// GetFallbackLanguage tries to obtain a requested language via the session,
// or the Accept-Language request header, or the LANG or LC_MESSAGES
// environment variables
func GetFallbackLanguage(c context.Context, r *http.Request, fallback ...string) string {
	if val, ok := c.Get(r, context.BaseCtxKey("session")); ok {
		sess := val.(context.Session)

		if language, ok := sess.Get("language"); ok {
			return language.(string)
		}
	}

	langs := lng.Parse(r.Header.Get("Accept-Language"))

	if len(langs) > 0 {
		return langs[0].String()
	}

	language := os.Getenv("LANG")

	if language == "" {
		language = os.Getenv("LC_MESSAGES")
		language = localeRegexp.ReplaceAllLiteralString(language, "")
	}

	if language == "" {
		if len(fallback) > 0 {
			language = fallback[0]
		} else {
			language = "en"
		}
	} else {
		langs := lng.Parse(language)
		if len(langs) > 0 {
			return langs[0].String()
		}
	}

	return language
}
Exemple #21
0
func (smw Session) Handler(ph http.Handler, c context.Context) http.Handler {
	var abspath string
	var maxAge, cleanupInterval, cleanupMaxAge time.Duration

	if filepath.IsAbs(smw.Path) {
		abspath = smw.Path
	} else {
		var err error
		abspath, err = filepath.Abs(path.Join(filepath.Dir(os.Args[0]), smw.Path))

		if err != nil {
			panic(err)
		}
	}

	if smw.MaxAge != "" {
		var err error
		maxAge, err = time.ParseDuration(smw.MaxAge)

		if err != nil {
			panic(err)
		}
	}

	logger := webfw.GetLogger(c)

	if smw.CleanupInterval != "" {
		var err error
		cleanupInterval, err = time.ParseDuration(smw.CleanupInterval)

		if err != nil {
			panic(err)
		}

		cleanupMaxAge, err = time.ParseDuration(smw.CleanupMaxAge)

		if err != nil {
			panic(err)
		}

		go func() {
			for _ = range time.Tick(cleanupInterval) {
				logger.Print("Cleaning up old sessions")

				if err := context.CleanupSessions(abspath, cleanupMaxAge); err != nil {
					logger.Printf("Failed to clean up sessions: %v", err)
				}
			}
		}()
	}

	handler := func(w http.ResponseWriter, r *http.Request) {
		uriParts := strings.SplitN(r.RequestURI, "?", 2)
		if uriParts[0] == "" {
			uriParts[0] = r.URL.Path
		}

		ignore := false
		for _, prefix := range smw.IgnoreURLPrefix {
			if prefix[0] == '/' {
				prefix = prefix[1:]
			}

			if strings.HasPrefix(uriParts[0], smw.Pattern+prefix+"/") {
				ignore = true
				break
			}

			if uriParts[0] == smw.Pattern+prefix {
				ignore = true
				break
			}
		}

		if ignore {
			ph.ServeHTTP(w, r)
			return
		}

		firstTimer := false
		var sess context.Session

		if smw.SessionGenerator == nil {
			sess = context.NewSession(smw.Secret, smw.Cipher, abspath)
		} else {
			sess = smw.SessionGenerator(smw.Secret, smw.Cipher, abspath)
		}
		sess.SetMaxAge(maxAge)

		err := sess.Read(r, c)

		if err != nil && err != context.ErrExpired && err != context.ErrNotExist {
			sess.SetName(util.UUID())
			firstTimer = true

			if err != context.ErrCookieNotExist {
				logger.Printf("Error reading session: %v", err)
			}
		}

		c.Set(r, context.BaseCtxKey("session"), sess)
		c.Set(r, context.BaseCtxKey("firstTimer"), firstTimer)

		rec := util.NewRecorderHijacker(w)

		ph.ServeHTTP(rec, r)

		for k, v := range rec.Header() {
			w.Header()[k] = v
		}

		if sess != nil {
			if err := sess.Write(w); err != nil {
				logger.Printf("Unable to write session: %v", err)
			}
		}

		w.WriteHeader(rec.GetCode())
		w.Write(rec.GetBody().Bytes())
	}

	return http.HandlerFunc(handler)
}
Exemple #22
0
func (mw Auth) Handler(ph http.Handler, c context.Context) http.Handler {
	logger := webfw.GetLogger(c)
	handler := func(w http.ResponseWriter, r *http.Request) {
		for _, prefix := range mw.IgnoreURLPrefix {
			if prefix[0] == '/' {
				prefix = prefix[1:]
			}

			if strings.HasPrefix(r.URL.Path, mw.Pattern+prefix+"/") {
				ph.ServeHTTP(w, r)
				return
			}
		}

		route, _, ok := webfw.GetDispatcher(c).RequestRoute(r)
		if !ok {
			ph.ServeHTTP(w, r)
			return
		}

		repo := GetRepo(c)

		switch ac := route.Controller.(type) {
		case AuthController:
			if !ac.LoginRequired(c, r) {
				ph.ServeHTTP(w, r)
				return
			}

			sess := webfw.GetSession(c, r)

			var u content.User
			validUser := false
			if uv, ok := sess.Get(AuthUserKey); ok {
				if u, ok = uv.(content.User); ok {
					validUser = true
				}
			}

			if !validUser {
				if uv, ok := sess.Get(AuthNameKey); ok {
					if n, ok := uv.(data.Login); ok {
						u = repo.UserByLogin(n)

						if u.HasErr() {
							logger.Print(u.Err())
						} else {
							validUser = true
							sess.Set(AuthUserKey, u)
						}
					}
				}
			}

			if validUser && !u.Data().Active {
				logger.Infoln("User " + u.Data().Login + " is inactive")
				validUser = false
			}

			if !validUser {
				d := webfw.GetDispatcher(c)
				sess.SetFlash(CtxKey("return-to"), r.URL.Path)
				path := d.NameToPath("auth-login", webfw.MethodGet)

				if path == "" {
					path = "/"
				}

				http.Redirect(w, r, path, http.StatusMovedPermanently)
				return
			}

		case ApiAuthController:
			if !ac.AuthRequired(c, r) {
				ph.ServeHTTP(w, r)
				return
			}

			url, login, signature, nonce, date, t := authData(r)

			validUser := false

			var u content.User

			if login != "" && signature != "" && !t.IsZero() {
				switch {
				default:
					u = repo.UserByLogin(data.Login(login))
					if u.HasErr() {
						logger.Printf("Error getting db user '%s': %v\n", login, u.Err())
						break
					}

					decoded, err := base64.StdEncoding.DecodeString(signature)
					if err != nil {
						logger.Printf("Error decoding auth header: %v\n", err)
						break
					}

					if t.Add(30 * time.Second).Before(time.Now()) {
						break
					}

					if !mw.Nonce.Check(nonce) {
						break
					}
					mw.Nonce.Remove(nonce)

					buf := util.BufferPool.GetBuffer()
					defer util.BufferPool.Put(buf)

					buf.ReadFrom(r.Body)
					r.Body = ioutil.NopCloser(buf)

					bodyHash := md5.New()
					if _, err := bodyHash.Write(buf.Bytes()); err != nil {
						logger.Printf("Error generating the hash for the request body: %v\n", err)
						break
					}

					contentMD5 := base64.StdEncoding.EncodeToString(bodyHash.Sum(nil))

					message := fmt.Sprintf("%s\n%s\n%s\n%s\n%s\n%s\n",
						url, r.Method, contentMD5, r.Header.Get("Content-Type"),
						date, nonce)

					b := make([]byte, base64.StdEncoding.EncodedLen(len(u.Data().MD5API)))
					base64.StdEncoding.Encode(b, u.Data().MD5API)

					hm := hmac.New(sha256.New, b)
					if _, err := hm.Write([]byte(message)); err != nil {
						logger.Printf("Error generating the hashed message: %v\n", err)
						break
					}

					if !hmac.Equal(hm.Sum(nil), decoded) {
						logger.Printf("Error matching the supplied auth message to the generated one.\n")
						break
					}

					if !u.Data().Active {
						logger.Println("User " + u.Data().Login + " is inactive")
						break
					}

					validUser = true
				}
			}

			if validUser {
				c.Set(r, context.BaseCtxKey("user"), u)
			} else {
				if rej, ok := ac.(AuthRejectHandler); ok {
					rej.AuthReject(c, r)
				} else {
					w.WriteHeader(http.StatusUnauthorized)
					return
				}
			}
		}

		ph.ServeHTTP(w, r)
	}

	return http.HandlerFunc(handler)
}
Exemple #23
0
func (mw Auth) Handler(ph http.Handler, c context.Context, l *log.Logger) http.Handler {
	handler := func(w http.ResponseWriter, r *http.Request) {
		for _, prefix := range mw.IgnoreURLPrefix {
			if prefix[0] == '/' {
				prefix = prefix[1:]
			}

			if strings.HasPrefix(r.URL.Path, mw.Pattern+prefix+"/") {
				ph.ServeHTTP(w, r)
				return
			}
		}

		route, _, ok := webfw.GetDispatcher(c).RequestRoute(r)
		if !ok {
			ph.ServeHTTP(w, r)
			return
		}

		switch ac := route.Controller.(type) {
		case AuthController:
			if !ac.LoginRequired(c, r) {
				ph.ServeHTTP(w, r)
				return
			}

			sess := webfw.GetSession(c, r)

			var u User
			validUser := false
			if uv, ok := sess.Get(authkey); ok {
				if u, ok = uv.(User); ok {
					validUser = true
				}
			}

			if !validUser {
				if uv, ok := sess.Get(namekey); ok {
					if n, ok := uv.(string); ok {
						var err error
						u, err = mw.DB.GetUser(n)

						if err == nil {
							validUser = true
							sess.Set(authkey, u)
						} else if _, ok := err.(ValidationError); !ok {
							l.Print(err)
						}
					}
				}
			}

			if validUser && !u.Active {
				Debug.Println("User " + u.Login + " is inactive")
				validUser = false
			}

			if !validUser {
				d := webfw.GetDispatcher(c)
				sess.SetFlash(CtxKey("return-to"), r.URL.Path)
				path := d.NameToPath("auth-login", webfw.MethodGet)

				if path == "" {
					path = "/"
				}

				http.Redirect(w, r, path, http.StatusMovedPermanently)
				return
			}

		case ApiAuthController:
			if !ac.AuthRequired(c, r) {
				ph.ServeHTTP(w, r)
				return
			}

			var u User
			var err error

			auth := r.Header.Get("Authorization")
			validUser := false

			if auth != "" {
				switch {
				default:
					if !strings.HasPrefix(auth, "Readeef ") {
						break
					}
					auth = auth[len("Readeef "):]

					parts := strings.SplitN(auth, ":", 2)
					login := parts[0]

					u, err = mw.DB.GetUser(login)
					if err != nil {
						l.Printf("Error getting db user '%s': %v\n", login, err)
						break
					}

					var decoded []byte
					decoded, err = base64.StdEncoding.DecodeString(parts[1])
					if err != nil {
						l.Printf("Error decoding auth header: %v\n", err)
						break
					}

					date := r.Header.Get("X-Date")
					t, err := time.Parse(http.TimeFormat, date)
					if err != nil || t.Add(30*time.Second).Before(time.Now()) {
						break
					}

					nonce := r.Header.Get("X-Nonce")
					if !mw.Nonce.Check(nonce) {
						break
					}
					mw.Nonce.Remove(nonce)

					buf := util.BufferPool.GetBuffer()
					defer util.BufferPool.Put(buf)

					buf.ReadFrom(r.Body)
					r.Body = ioutil.NopCloser(buf)

					bodyHash := md5.New()
					if _, err := bodyHash.Write(buf.Bytes()); err != nil {
						l.Printf("Error generating the hash for the request body: %v\n", err)
						break
					}

					contentMD5 := base64.StdEncoding.EncodeToString(bodyHash.Sum(nil))

					message := fmt.Sprintf("%s\n%s\n%s\n%s\n%s\n%s\n",
						r.RequestURI, r.Method, contentMD5, r.Header.Get("Content-Type"),
						date, nonce)

					b := make([]byte, base64.StdEncoding.EncodedLen(len(u.MD5API)))
					base64.StdEncoding.Encode(b, u.MD5API)

					hm := hmac.New(sha256.New, b)
					if _, err := hm.Write([]byte(message)); err != nil {
						l.Printf("Error generating the hashed message: %v\n", err)
						break
					}

					if !hmac.Equal(hm.Sum(nil), decoded) {
						l.Printf("Error matching the supplied auth message to the generated one.\n")
						break
					}

					if !u.Active {
						Debug.Println("User " + u.Login + " is inactive")
						break
					}

					validUser = true
				}
			}

			if !validUser {
				w.WriteHeader(http.StatusForbidden)
				return
			}

			c.Set(r, context.BaseCtxKey("user"), u)
		}

		ph.ServeHTTP(w, r)
	}

	return http.HandlerFunc(handler)
}
Exemple #24
0
func (controller TtRss) Handler(c context.Context) http.Handler {
	repo := readeef.GetRepo(c)
	logger := webfw.GetLogger(c)
	config := readeef.GetConfig(c)

	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		action := webfw.GetMultiPatternIdentifier(c, r)

		if action == "redirecter" {
			http.Redirect(w, r, "/", http.StatusMovedPermanently)
		}

		req := ttRssRequest{}

		resp := ttRssResponse{}

		var err error
		var errType string
		var user content.User
		var con interface{}

		switch {
		default:
			var b []byte
			in := map[string]interface{}{}

			if b, err = ioutil.ReadAll(r.Body); err != nil {
				err = fmt.Errorf("reading request body: %s", err)
				break
			}

			if err = json.Unmarshal(b, &in); err != nil {
				err = fmt.Errorf("decoding JSON request: %s", err)
				break
			}

			req = ttRssConvertRequest(in)

			logger.Debugf("Request: %#v\n", req)

			resp.Seq = req.Seq

			if req.Op != "login" && req.Op != "isLoggedIn" {
				if sess, ok := ttRssSessions[req.Sid]; ok {
					user = repo.UserByLogin(data.Login(sess.login))
					if repo.Err() != nil {
						errType = "NOT_LOGGED_IN"
					} else {
						sess.lastVisit = time.Now()
						ttRssSessions[req.Sid] = sess
					}
				} else {
					errType = "NOT_LOGGED_IN"
				}
			}

			if errType != "" {
				logger.Debugf("TT-RSS Sessions: %#v\n", ttRssSessions)
				break
			}

			logger.Debugf("TT-RSS OP: %s\n", req.Op)
			switch req.Op {
			case "getApiLevel":
				con = ttRssGenericContent{Level: TTRSS_API_LEVEL}
			case "getVersion":
				con = ttRssGenericContent{Version: TTRSS_VERSION}
			case "login":
				user = repo.UserByLogin(data.Login(req.User))
				if repo.Err() != nil {
					errType = "LOGIN_ERROR"
					err = fmt.Errorf("getting TT-RSS user: %s", repo.Err())
					break
				}

				if !user.Authenticate(req.Password, []byte(config.Auth.Secret)) {
					errType = "LOGIN_ERROR"
					err = fmt.Errorf("authentication for TT-RSS user '%s'", user.Data().Login)
					break
				}

				var sessId string

				login := user.Data().Login

				for id, sess := range ttRssSessions {
					if sess.login == login {
						sessId = id
					}
				}

				if sessId == "" {
					sessId = strings.Replace(util.UUID(), "-", "", -1)
					ttRssSessions[sessId] = ttRssSession{login: login, lastVisit: time.Now()}
				}

				con = ttRssGenericContent{
					ApiLevel:  TTRSS_API_LEVEL,
					SessionId: sessId,
				}
			case "logout":
				delete(ttRssSessions, req.Sid)
				con = ttRssGenericContent{Status: "OK"}
			case "isLoggedIn":
				if _, ok := ttRssSessions[req.Sid]; ok {
					con = ttRssGenericContent{Status: true}
				} else {
					con = ttRssGenericContent{Status: false}
				}
			case "getUnread":
				var ar content.ArticleRepo
				o := data.ArticleCountOptions{UnreadOnly: true}

				if req.IsCat {
					tagId := data.TagId(req.FeedId)
					if tagId > 0 {
						ar = user.TagById(tagId)
					} else if tagId == TTRSS_CAT_UNCATEGORIZED {
						ar = user
						o.UntaggedOnly = true
					} else if tagId == TTRSS_CAT_SPECIAL {
						ar = user
						o.FavoriteOnly = true
					}
				} else {
					switch req.FeedId {
					case TTRSS_FAVORITE_ID:
						ar = user
						o.FavoriteOnly = true
					case TTRSS_FRESH_ID:
						ar = user
						o.AfterDate = time.Now().Add(TTRSS_FRESH_DURATION)
					case TTRSS_ALL_ID, 0:
						ar = user
					default:
						if req.FeedId > 0 {
							feed := user.FeedById(req.FeedId)
							if feed.HasErr() {
								err = feed.Err()
								break
							}

							ar = feed
						}

					}

				}

				if ar == nil {
					con = ttRssGenericContent{Unread: "0"}
				} else if con == nil {
					con = ttRssGenericContent{Unread: strconv.FormatInt(ar.Count(o), 10)}
				}
			case "getCounters":
				if req.OutputMode == "" {
					req.OutputMode = "flc"
				}
				cContent := ttRssCountersContent{}

				o := data.ArticleCountOptions{UnreadOnly: true}
				unreadCount := user.Count(o)
				cContent = append(cContent,
					ttRssCounter{Id: "global-unread", Counter: unreadCount})

				feeds := user.AllFeeds()
				cContent = append(cContent,
					ttRssCounter{Id: "subscribed-feeds", Counter: int64(len(feeds))})

				cContent = append(cContent, ttRssCounter{Id: TTRSS_ARCHIVED_ID})

				cContent = append(cContent,
					ttRssCounter{Id: TTRSS_FAVORITE_ID,
						Counter:    user.Count(data.ArticleCountOptions{UnreadOnly: true, FavoriteOnly: true}),
						AuxCounter: user.Count(data.ArticleCountOptions{FavoriteOnly: true})})

				cContent = append(cContent, ttRssCounter{Id: TTRSS_PUBLISHED_ID})

				freshTime := time.Now().Add(TTRSS_FRESH_DURATION)
				cContent = append(cContent,
					ttRssCounter{Id: TTRSS_FRESH_ID,
						Counter:    user.Count(data.ArticleCountOptions{UnreadOnly: true, AfterDate: freshTime}),
						AuxCounter: 0})

				cContent = append(cContent,
					ttRssCounter{Id: TTRSS_ALL_ID,
						Counter:    user.Count(),
						AuxCounter: 0})

				for _, f := range feeds {
					cContent = append(cContent,
						ttRssCounter{Id: int64(f.Data().Id), Counter: f.Count(o)},
					)

				}

				cContent = append(cContent, ttRssCounter{Id: TTRSS_CAT_LABELS, Counter: 0, Kind: "cat"})

				for _, t := range user.Tags() {
					cContent = append(cContent,
						ttRssCounter{
							Id:      int64(t.Data().Id),
							Counter: t.Count(o),
							Kind:    "cat",
						},
					)
				}

				cContent = append(cContent,
					ttRssCounter{
						Id:      TTRSS_CAT_UNCATEGORIZED,
						Counter: user.Count(data.ArticleCountOptions{UnreadOnly: true, UntaggedOnly: true}),
						Kind:    "cat",
					},
				)

				if user.HasErr() {
					err = fmt.Errorf("Error getting user counters: %v\n", user.Err())
				}

				con = cContent
			case "getFeeds":
				fContent := ttRssFeedsContent{}

				if req.CatId == TTRSS_CAT_ALL || req.CatId == TTRSS_CAT_SPECIAL {
					unreadFav := user.Count(data.ArticleCountOptions{UnreadOnly: true, FavoriteOnly: true})

					if unreadFav > 0 || !req.UnreadOnly {
						fContent = append(fContent, ttRssFeed{
							Id:     TTRSS_FAVORITE_ID,
							Title:  ttRssSpecialTitle(TTRSS_FAVORITE_ID),
							Unread: unreadFav,
							CatId:  TTRSS_FAVORITE_ID,
						})
					}

					freshTime := time.Now().Add(TTRSS_FRESH_DURATION)
					unreadFresh := user.Count(data.ArticleCountOptions{UnreadOnly: true, AfterDate: freshTime})

					if unreadFresh > 0 || !req.UnreadOnly {
						fContent = append(fContent, ttRssFeed{
							Id:     TTRSS_FRESH_ID,
							Title:  ttRssSpecialTitle(TTRSS_FRESH_ID),
							Unread: unreadFresh,
							CatId:  TTRSS_FAVORITE_ID,
						})
					}

					unreadAll := user.Count(data.ArticleCountOptions{UnreadOnly: true})

					if unreadAll > 0 || !req.UnreadOnly {
						fContent = append(fContent, ttRssFeed{
							Id:     TTRSS_ALL_ID,
							Title:  ttRssSpecialTitle(TTRSS_ALL_ID),
							Unread: unreadAll,
							CatId:  TTRSS_FAVORITE_ID,
						})
					}
				}

				var feeds []content.UserFeed
				var catId int
				if req.CatId == TTRSS_CAT_ALL || req.CatId == TTRSS_CAT_ALL_EXCEPT_VIRTUAL {
					feeds = user.AllFeeds()
				} else {
					if req.CatId == TTRSS_CAT_UNCATEGORIZED {
						tagged := user.AllTaggedFeeds()
						for _, t := range tagged {
							if len(t.Tags()) == 0 {
								feeds = append(feeds, t)
							}
						}
					} else if req.CatId > 0 {
						catId = int(req.CatId)
						t := user.TagById(req.CatId)
						tagged := t.AllFeeds()
						if t.HasErr() {
							err = t.Err()
							break
						}
						for _, t := range tagged {
							feeds = append(feeds, t)
						}
					}
				}

				if len(feeds) > 0 {
					o := data.ArticleCountOptions{UnreadOnly: true}
					for i := range feeds {
						if req.Limit > 0 {
							if i < req.Offset || i >= req.Limit+req.Offset {
								continue
							}
						}

						d := feeds[i].Data()
						unread := feeds[i].Count(o)

						if unread > 0 || !req.UnreadOnly {
							fContent = append(fContent, ttRssFeed{
								Id:          d.Id,
								Title:       d.Title,
								FeedUrl:     d.Link,
								CatId:       catId,
								Unread:      unread,
								LastUpdated: time.Now().Unix(),
								OrderId:     0,
							})
						}
					}
				}

				if user.HasErr() {
					err = fmt.Errorf("Error getting user feeds: %v\n", user.Err())
				}

				con = fContent
			case "getCategories":
				cContent := ttRssCategoriesContent{}
				o := data.ArticleCountOptions{UnreadOnly: true}

				for _, t := range user.Tags() {
					td := t.Data()
					count := t.Count(o)

					if count > 0 || !req.UnreadOnly {
						cContent = append(cContent,
							ttRssCat{Id: strconv.FormatInt(int64(td.Id), 10), Title: string(td.Value), Unread: count},
						)
					}
				}

				count := user.Count(data.ArticleCountOptions{UnreadOnly: true, UntaggedOnly: true})
				if count > 0 || !req.UnreadOnly {
					cContent = append(cContent,
						ttRssCat{Id: strconv.FormatInt(TTRSS_CAT_UNCATEGORIZED, 10), Title: "Uncategorized", Unread: count},
					)
				}

				o.FavoriteOnly = true
				count = user.Count(o)

				if count > 0 || !req.UnreadOnly {
					cContent = append(cContent,
						ttRssCat{Id: strconv.FormatInt(TTRSS_CAT_SPECIAL, 10), Title: "Special", Unread: count},
					)
				}

				con = cContent
			case "getHeadlines":
				if req.FeedId == 0 {
					errType = "INCORRECT_USAGE"
					break
				}

				limit := req.Limit
				if limit == 0 {
					limit = 200
				}

				var articles []content.UserArticle
				var articleRepo content.ArticleRepo
				var feedTitle string
				firstId := data.ArticleId(0)
				o := data.ArticleQueryOptions{Limit: limit, Offset: req.Skip, UnreadFirst: true, SkipSessionProcessors: true}

				if req.IsCat {
					if req.FeedId == TTRSS_CAT_UNCATEGORIZED {
						ttRssSetupSorting(req, user)
						articleRepo = user
						o.UntaggedOnly = true
						feedTitle = "Uncategorized"
					} else if req.FeedId > 0 {
						t := user.TagById(data.TagId(req.FeedId))
						ttRssSetupSorting(req, t)
						articleRepo = t
						feedTitle = string(t.Data().Value)
					}
				} else {
					if req.FeedId == TTRSS_FAVORITE_ID {
						ttRssSetupSorting(req, user)
						o.FavoriteOnly = true
						articleRepo = user
						feedTitle = "Starred articles"
					} else if req.FeedId == TTRSS_FRESH_ID {
						ttRssSetupSorting(req, user)
						o.AfterDate = time.Now().Add(TTRSS_FRESH_DURATION)
						articleRepo = user
						feedTitle = "Fresh articles"
					} else if req.FeedId == TTRSS_ALL_ID {
						ttRssSetupSorting(req, user)
						articleRepo = user
						feedTitle = "All articles"
					} else if req.FeedId > 0 {
						feed := user.FeedById(req.FeedId)

						ttRssSetupSorting(req, feed)
						articleRepo = feed
						feedTitle = feed.Data().Title
					}
				}

				if req.SinceId > 0 {
					o.AfterId = req.SinceId
				}

				if articleRepo != nil {
					if req.Search != "" {
						if controller.sp != nil {
							if as, ok := articleRepo.(content.ArticleSearch); ok {
								articles = as.Query(req.Search, controller.sp, limit, req.Skip)
							}
						}
					} else {
						var skip bool

						switch req.ViewMode {
						case "all_articles":
						case "adaptive":
						case "unread":
							o.UnreadOnly = true
						case "marked":
							o.FavoriteOnly = true
						default:
							skip = true
						}

						if !skip {
							articles = articleRepo.Articles(o)
						}
					}
				}

				if len(articles) > 0 {
					firstId = articles[0].Data().Id
				}

				headlines := ttRssHeadlinesFromArticles(articles, feedTitle, req.ShowContent, req.ShowExcerpt)
				if req.IncludeHeader {
					header := ttRssHeadlinesHeader{Id: req.FeedId, FirstId: firstId, IsCat: req.IsCat}
					hContent := ttRssHeadlinesHeaderContent{}

					hContent = append(hContent, header)
					hContent = append(hContent, headlines)

					con = hContent
				} else {
					con = headlines
				}
			case "updateArticle":
				articles := user.ArticlesById(req.ArticleIds, data.ArticleQueryOptions{SkipSessionProcessors: true})
				updateCount := int64(0)

				switch req.Field {
				case 0, 2:
					for _, a := range articles {
						d := a.Data()
						updated := false

						switch req.Field {
						case 0:
							switch req.Mode {
							case 0:
								if d.Favorite {
									updated = true
									d.Favorite = false
								}
							case 1:
								if !d.Favorite {
									updated = true
									d.Favorite = true
								}
							case 2:
								updated = true
								d.Favorite = !d.Favorite
							}
							if updated {
								a.Favorite(d.Favorite)
							}
						case 2:
							switch req.Mode {
							case 0:
								if !d.Read {
									updated = true
									d.Read = true
								}
							case 1:
								if d.Read {
									updated = true
									d.Read = false
								}
							case 2:
								updated = true
								d.Read = !d.Read
							}
							if updated {
								a.Read(d.Read)
							}
						}

						if updated {
							if a.HasErr() {
								err = a.Err()
								break
							}

							updateCount++
						}
					}

					if err != nil {
						break
					}

					con = ttRssGenericContent{Status: "OK", Updated: updateCount}
				}
			case "getArticle":
				articles := user.ArticlesById(req.ArticleId, data.ArticleQueryOptions{SkipSessionProcessors: true})
				feedTitles := map[data.FeedId]string{}

				for _, a := range articles {
					d := a.Data()
					if _, ok := feedTitles[d.FeedId]; !ok {
						f := repo.FeedById(d.FeedId)
						feedTitles[d.FeedId] = f.Data().Title
					}
				}

				cContent := ttRssArticlesContent{}

				for _, a := range articles {
					d := a.Data()
					title := feedTitles[d.FeedId]
					h := ttRssArticle{
						Id:        strconv.FormatInt(int64(d.Id), 10),
						Unread:    !d.Read,
						Marked:    d.Favorite,
						Updated:   d.Date.Unix(),
						Title:     d.Title,
						Link:      d.Link,
						FeedId:    strconv.FormatInt(int64(d.FeedId), 10),
						FeedTitle: title,
						Content:   d.Description,
					}

					cContent = append(cContent, h)
				}

				con = cContent
			case "getConfig":
				con = ttRssConfigContent{DaemonIsRunning: true, NumFeeds: len(user.AllFeeds())}
			case "updateFeed":
				con = ttRssGenericContent{Status: "OK"}
			case "catchupFeed":
				var ar content.ArticleRepo
				o := data.ArticleUpdateStateOptions{BeforeDate: time.Now()}

				if req.IsCat {
					tagId := data.TagId(req.FeedId)
					ar = user.TagById(tagId)

					if tagId == TTRSS_CAT_UNCATEGORIZED {
						o.UntaggedOnly = true
					}
				} else {
					ar = user.FeedById(req.FeedId)
				}

				if ar != nil {
					ar.ReadState(true, o)

					if e, ok := ar.(content.Error); ok {
						if e.HasErr() {
							err = e.Err()
							break
						}
					}

					con = ttRssGenericContent{Status: "OK"}
				}
			case "getPref":
				switch req.PrefName {
				case "DEFAULT_UPDATE_INTERVAL":
					con = ttRssGenericContent{Value: int(config.FeedManager.Converted.UpdateInterval.Minutes())}
				case "DEFAULT_ARTICLE_LIMIT":
					con = ttRssGenericContent{Value: 200}
				case "HIDE_READ_FEEDS":
					con = ttRssGenericContent{Value: user.Data().ProfileData["unreadOnly"]}
				case "FEEDS_SORT_BY_UNREAD", "ENABLE_FEED_CATS", "SHOW_CONTENT_PREVIEW":
					con = ttRssGenericContent{Value: true}
				case "FRESH_ARTICLE_MAX_AGE":
					con = ttRssGenericContent{Value: (-1 * TTRSS_FRESH_DURATION).Hours()}
				}
			case "getLabels":
				con = []interface{}{}
			case "setArticleLabel":
				con = ttRssGenericContent{Status: "OK", Updated: 0}
			case "shareToPublished":
				errType = "Publishing failed"
			case "subscribeToFeed":
				f := repo.FeedByLink(req.FeedUrl)
				for _, u := range f.Users() {
					if u.Data().Login == user.Data().Login {
						con = ttRssSubscribeContent{Status: struct {
							Code int `json:"code"`
						}{0}}
						break
					}
				}

				if f.HasErr() {
					err = f.Err()
					break
				}

				f, err := controller.fm.AddFeedByLink(req.FeedUrl)
				if err != nil {
					errType = "INCORRECT_USAGE"
					break
				}

				uf := user.AddFeed(f)
				if uf.HasErr() {
					err = uf.Err()
					break
				}

				con = ttRssSubscribeContent{Status: struct {
					Code int `json:"code"`
				}{1}}
			case "unsubscribeFeed":
				f := user.FeedById(req.FeedId)
				f.Detach()
				users := f.Users()

				if f.HasErr() {
					err = f.Err()
					if err == content.ErrNoContent {
						errType = "FEED_NOT_FOUND"
					}
					break
				}

				if len(users) == 0 {
					controller.fm.RemoveFeed(f)
				}

				con = ttRssGenericContent{Status: "OK"}
			case "getFeedTree":
				items := []ttRssCategory{}

				special := ttRssCategory{Id: "CAT:-1", Items: []ttRssCategory{}, Name: "Special", Type: "category", BareId: -1}

				special.Items = append(special.Items, ttRssFeedListCategoryFeed(user, nil, TTRSS_ALL_ID, false))
				special.Items = append(special.Items, ttRssFeedListCategoryFeed(user, nil, TTRSS_FRESH_ID, false))
				special.Items = append(special.Items, ttRssFeedListCategoryFeed(user, nil, TTRSS_FAVORITE_ID, false))
				special.Items = append(special.Items, ttRssFeedListCategoryFeed(user, nil, TTRSS_PUBLISHED_ID, false))
				special.Items = append(special.Items, ttRssFeedListCategoryFeed(user, nil, TTRSS_ARCHIVED_ID, false))
				special.Items = append(special.Items, ttRssFeedListCategoryFeed(user, nil, TTRSS_RECENTLY_READ_ID, false))

				items = append(items, special)

				tf := user.AllTaggedFeeds()

				uncat := ttRssCategory{Id: "CAT:0", Items: []ttRssCategory{}, BareId: 0, Name: "Uncategorized", Type: "category"}
				tagCategories := map[content.Tag]ttRssCategory{}

				for _, f := range tf {
					tags := f.Tags()

					item := ttRssFeedListCategoryFeed(user, f, f.Data().Id, true)
					if len(tags) > 0 {
						for _, t := range tags {
							var c ttRssCategory
							if cached, ok := tagCategories[t]; ok {
								c = cached
							} else {
								c = ttRssCategory{
									Id:     "CAT:" + strconv.FormatInt(int64(t.Data().Id), 10),
									BareId: data.FeedId(t.Data().Id),
									Name:   string(t.Data().Value),
									Type:   "category",
									Items:  []ttRssCategory{},
								}
							}

							c.Items = append(c.Items, item)
							tagCategories[t] = c
						}
					} else {
						uncat.Items = append(uncat.Items, item)
					}
				}

				categories := []ttRssCategory{uncat}
				for _, c := range tagCategories {
					categories = append(categories, c)
				}

				for _, c := range categories {
					if len(c.Items) == 1 {
						c.Param = "(1 feed)"
					} else {
						c.Param = fmt.Sprintf("(%d feed)", len(c.Items))
					}
					items = append(items, c)
				}

				fl := ttRssCategory{Identifier: "id", Label: "name"}
				fl.Items = items

				if user.HasErr() {
					err = user.Err()
				} else {
					con = ttRssFeedTreeContent{Categories: fl}
				}
			default:
				errType = "UNKNOWN_METHOD"
				con = ttRssGenericContent{Method: req.Op}
			}
		}

		if err == nil && errType == "" {
			resp.Status = TTRSS_API_STATUS_OK
		} else {
			logger.Infof("Error processing TT-RSS API request: %s %v\n", errType, err)
			resp.Status = TTRSS_API_STATUS_ERR
			con = ttRssErrorContent{Error: errType}
		}

		var b []byte
		b, err = json.Marshal(con)
		if err == nil {
			resp.Content = json.RawMessage(b)
		}

		b, err = json.Marshal(&resp)

		if err == nil {
			w.Header().Set("Content-Type", "text/json")
			w.Header().Set("Api-Content-Length", strconv.Itoa(len(b)))
			w.Write(b)

			logger.Debugf("Output for %s: %s\n", req.Op, string(b))
		} else {
			logger.Print(fmt.Errorf("TT-RSS error %s: %v", req.Op, err))

			w.WriteHeader(http.StatusInternalServerError)
		}

	})
}
Exemple #25
0
func (con WebSocket) AuthReject(c context.Context, r *http.Request) {
	c.Set(r, readeef.CtxKey("forbidden"), true)
}
Exemple #26
0
func (imw I18N) Handler(ph http.Handler, c context.Context) http.Handler {
	for _, l := range imw.Languages {
		file, err := fs.DefaultFS.OpenRoot(imw.Dir, l+".all.json")
		if err == nil {
			var b []byte

			if b, err = ioutil.ReadAll(file); err == nil {
				err = i18n.ParseTranslationFileBytes(l+".all.json", b)
			}
		}

		if err != nil {
			panic(fmt.Sprintf("Error opening locale file '%s.all.json': %v\n", l, err))
		}
	}

	renderer := webfw.GetRenderer(c)
	renderer.Funcs(imw.TemplateFuncMap())

	handler := func(w http.ResponseWriter, r *http.Request) {
		c.Set(r, context.BaseCtxKey("langs"), imw.Languages)

		if len(imw.Languages) == 0 {
			c.Set(r, context.BaseCtxKey("lang"), "")
			ph.ServeHTTP(w, r)
			return
		}

		found := false

		uriParts := strings.SplitN(r.RequestURI, "?", 2)
		if uriParts[0] == "" {
			uriParts[0] = r.URL.Path
		}
		for _, prefix := range imw.IgnoreURLPrefix {
			if prefix[0] == '/' {
				prefix = prefix[1:]
			}

			if strings.HasPrefix(uriParts[0], imw.Pattern+prefix+"/") {
				found = true
				break
			}

			if uriParts[0] == imw.Pattern+prefix {
				found = true
				break
			}
		}

		if !found {
			for _, language := range imw.Languages {
				if uriParts[0] == imw.Pattern+language {
					url := uriParts[0] + "/"
					if len(uriParts) > 1 && uriParts[1] != "" {
						url += "?" + uriParts[1]
					}

					http.Redirect(w, r, url, http.StatusFound)

					return
				}

				if strings.HasPrefix(uriParts[0], imw.Pattern+language+"/") {
					r.URL.Path = imw.Pattern + r.URL.Path[len(imw.Pattern+language+"/"):]

					uriParts[0] = imw.Pattern + uriParts[0][len(imw.Pattern+language+"/"):]

					r.RequestURI = strings.Join(uriParts, "?")

					c.Set(r, context.BaseCtxKey("lang"), language)
					found = true

					s := webfw.GetSession(c, r)
					s.Set("language", language)

					break
				}
			}
		}

		if !found {
			fallback := webfw.GetFallbackLanguage(c, r, imw.FallbackLanguage)
			index := strings.Index(fallback, "-")
			short := fallback
			if index > -1 {
				short = fallback[:index]
			}
			foundShort := false

			for _, language := range imw.Languages {
				if language == fallback {
					found = true
					break
				}

				if language == short {
					foundShort = true
				}
			}

			var language string
			if found {
				language = fallback
			} else if foundShort {
				language = short
			} else {
				language = imw.FallbackLanguage
			}

			url := imw.Pattern + language + uriParts[0][len(imw.Pattern)-1:]
			if len(uriParts) > 1 && uriParts[1] != "" {
				url += "?" + uriParts[1]
			}

			http.Redirect(w, r, url, http.StatusFound)

			return
		}

		ph.ServeHTTP(w, r)
	}

	return http.HandlerFunc(handler)
}
Exemple #27
0
// GetNamedForward returns a name, used by the dispatcher to lookup a route to
// forward to.
func GetNamedForward(c context.Context, r *http.Request) string {
	if val, ok := c.Get(r, context.BaseCtxKey("named-forward")); ok {
		return val.(string)
	}
	return ""
}
Exemple #28
0
// GetMultiPatternIdentifier returns the identifier for the current
// multi-pattern route.
func GetMultiPatternIdentifier(c context.Context, r *http.Request) string {
	if val, ok := c.Get(r, context.BaseCtxKey("multi-pattern-identifier")); ok {
		return val.(string)
	}
	return ""
}
Exemple #29
0
// GetDispatcher returns the request dispatcher.
func GetDispatcher(c context.Context) *Dispatcher {
	if val, ok := c.GetGlobal(context.BaseCtxKey("dispatcher")); ok {
		return val.(*Dispatcher)
	}
	return &Dispatcher{}
}