Feedback related features

Introduced classes

abstract class APIFeedBack

nitc :: APIFeedBack

Base handler for feedback features.
class APIStars

nitc :: APIStars

Stars attributed to mentities
class APIStarsBest

nitc :: APIStarsBest

Best rated entities
class APIStarsDimension

nitc :: APIStarsDimension

Stars attributed to mentities by dimension
class APIStarsMost

nitc :: APIStarsMost

Most rated entities
class APIStarsUsers

nitc :: APIStarsUsers

Best rated entities
class APIStarsWorst

nitc :: APIStarsWorst

Best rated entities
class APIUserStars

nitc :: APIUserStars

Stars attributed to mentities by user
class StarRating

nitc :: StarRating

Star ratings allow users to rate mentities with a 5-stars system.
class StarRatingRepo

nitc :: StarRatingRepo

StarRating Mongo Repository

Redefined classes

redef class APIRouter

nitc :: api_feedback $ APIRouter

A Rooter dedicated to APIHandlers.
redef abstract class Deserializer

nitc :: api_feedback $ Deserializer

Abstract deserialization service
redef abstract class MEntity

nitc :: api_feedback $ MEntity

A named and possibly documented entity in the model.
redef class NitwebConfig

nitc :: api_feedback $ NitwebConfig

Nitweb config file.
redef class User

nitc :: api_feedback $ User

A Github user

All class definitions

abstract class APIFeedBack

nitc $ APIFeedBack

Base handler for feedback features.
redef class APIRouter

nitc :: api_feedback $ APIRouter

A Rooter dedicated to APIHandlers.
class APIStars

nitc $ APIStars

Stars attributed to mentities
class APIStarsBest

nitc $ APIStarsBest

Best rated entities
class APIStarsDimension

nitc $ APIStarsDimension

Stars attributed to mentities by dimension
class APIStarsMost

nitc $ APIStarsMost

Most rated entities
class APIStarsUsers

nitc $ APIStarsUsers

Best rated entities
class APIStarsWorst

nitc $ APIStarsWorst

Best rated entities
class APIUserStars

nitc $ APIUserStars

Stars attributed to mentities by user
redef abstract class Deserializer

nitc :: api_feedback $ Deserializer

Abstract deserialization service
redef abstract class MEntity

nitc :: api_feedback $ MEntity

A named and possibly documented entity in the model.
redef class NitwebConfig

nitc :: api_feedback $ NitwebConfig

Nitweb config file.
class StarRating

nitc $ StarRating

Star ratings allow users to rate mentities with a 5-stars system.
class StarRatingRepo

nitc $ StarRatingRepo

StarRating Mongo Repository
redef class User

nitc :: api_feedback $ User

A Github user
package_diagram nitc::api_feedback api_feedback nitc::api_base api_base nitc::api_feedback->nitc::api_base popcorn::pop_auth pop_auth nitc::api_feedback->popcorn::pop_auth popcorn popcorn nitc::api_base->popcorn popcorn::pop_repos pop_repos nitc::api_base->popcorn::pop_repos popcorn::pop_json pop_json nitc::api_base->popcorn::pop_json nitc::commands_http commands_http nitc::api_base->nitc::commands_http nitc::json_commands json_commands nitc::api_base->nitc::json_commands nitc::html_commands html_commands nitc::api_base->nitc::html_commands popcorn::pop_auth->popcorn::pop_json popcorn::pop_sessions pop_sessions popcorn::pop_auth->popcorn::pop_sessions github github popcorn::pop_auth->github ...popcorn ... ...popcorn->popcorn ...popcorn::pop_repos ... ...popcorn::pop_repos->popcorn::pop_repos ...popcorn::pop_json ... ...popcorn::pop_json->popcorn::pop_json ...nitc::commands_http ... ...nitc::commands_http->nitc::commands_http ...nitc::json_commands ... ...nitc::json_commands->nitc::json_commands ...nitc::html_commands ... ...nitc::html_commands->nitc::html_commands ...popcorn::pop_sessions ... ...popcorn::pop_sessions->popcorn::pop_sessions ...github ... ...github->github nitc::api api nitc::api->nitc::api_feedback nitc::nitweb nitweb nitc::nitweb->nitc::api nitc::nitweb... ... nitc::nitweb...->nitc::nitweb

Ancestors

module abstract_collection

core :: abstract_collection

Abstract collection classes and services.
module abstract_text

core :: abstract_text

Abstract class for manipulation of sequences of characters
module abstract_tree

trees :: abstract_tree

Introduce tree structures abstraction
module actors_injection_phase

nitc :: actors_injection_phase

Injects model for the classes annotated with "is actor" so
module annotation

nitc :: annotation

Management and utilities on annotations
module api

github :: api

Nit object oriented interface to Github api.
module array

core :: array

This module introduces the standard array structure.
module astbuilder

nitc :: astbuilder

Instantiation and transformation of semantic nodes in the AST of expressions and statements
module astutil

nitc :: astutil

Additional features on Nit AST
module auto_super_init

nitc :: auto_super_init

Computing of super-constructors that must be implicitly called at the begin of constructors.
module base64

base64 :: base64

Offers the base 64 encoding and decoding algorithms
module bintree

trees :: bintree

Binary Tree data-structure
module bitset

core :: bitset

Services to handle BitSet
module bktree

trees :: bktree

Implementation of BKTree
module bootstrap

html :: bootstrap

HTML templates for Bootstrap components.
module bytes

core :: bytes

Services for byte streams and arrays
module c

c :: c

Structures and services for compatibility with the C language
module cache

github :: cache

Enable caching on Github API accesses.
module caching

serialization :: caching

Services for caching serialization engines
module catalog

nitc :: catalog

Basic catalog generator for Nit packages
module check_annotation

nitc :: check_annotation

Check that annotation present in the AST are either primitive or user-declared
module circular_array

core :: circular_array

Efficient data structure to access both end of the sequence.
module codec_base

core :: codec_base

Base for codecs to use with streams
module codecs

core :: codecs

Group module for all codec-related manipulations
module collection

core :: collection

This module define several collection classes.
module commands_base

nitc :: commands_base

Documentation commands
module commands_catalog

nitc :: commands_catalog

Commands to retrieve Catalog related data
module commands_docdown

nitc :: commands_docdown

Doc down related queries
module commands_graph

nitc :: commands_graph

Graph commands
module commands_http

nitc :: commands_http

Initialize commands from HTTP requests
module commands_model

nitc :: commands_model

Doc commands about a Model or a MEntity
module commands_parser

nitc :: commands_parser

A parser that create DocCommand from a string
module commands_usage

nitc :: commands_usage

Commands about how mentities are used
module config

config :: config

Configuration options for nit tools and apps
module console

console :: console

Defines some ANSI Terminal Control Escape Sequences.
module core

core :: core

Standard classes and methods used by default by Nit programs and libraries.
module counter

counter :: counter

Simple numerical statistical analysis and presentation
module csv

csv :: csv

CSV document handling.
module curl

curl :: curl

Data transfer powered by the native curl library
module deriving

nitc :: deriving

Injection of automatic method definitions for standard methods, based on the attributes of the classes
module digraph

graph :: digraph

Implementation of directed graphs, also called digraphs.
module div_by_zero

nitc :: div_by_zero

Detection of divisions by zero in obvious cases
module dot

dot :: dot

Dot rendering library
module engine_tools

serialization :: engine_tools

Advanced services for serialization engines
module environ

core :: environ

Access to the environment variables of the process
module error

core :: error

Standard error-management infrastructure.
module error

json :: error

Intro JsonParseError which is exposed by all JSON reading APIs
module exec

core :: exec

Invocation and management of operating system sub-processes.
module file

core :: file

File manipulations (create, read, write, etc.)
module file_server

nitcorn :: file_server

Provides the FileServer action, which is a standard and minimal file server
module fixed_ints

core :: fixed_ints

Basic integers of fixed-precision
module fixed_ints_text

core :: fixed_ints_text

Text services to complement fixed_ints
module flat

core :: flat

All the array-based text representations
module flow

nitc :: flow

Intraprocedural static flow.
module frontend

nitc :: frontend

Collect and orchestration of main frontend phases
module gc

core :: gc

Access to the Nit internal garbage collection mechanism
module github

github :: github

Nit wrapper for Github API
module glsl_validation

nitc :: glsl_validation

Check shader code within Nit modules using the tool glslangValidator
module hash_collection

core :: hash_collection

Introduce HashMap and HashSet.
module highlight

nitc :: highlight

Highlighting of Nit AST
module html

html :: html

HTML output facilities
module html_commands

nitc :: html_commands

Render commands results as HTML
module html_model

nitc :: html_model

Translate mentities to html blocks.
module htmlight

nitc :: htmlight

Highlighting of Nit AST with HTML
module http_errors

nitcorn :: http_errors

Offers ErrorTemplate to display error pages
module http_request

nitcorn :: http_request

Provides the HttpRequest class and services to create it
module http_request_buffer

nitcorn :: http_request_buffer

Http request parsing for buffered inputs.
module http_response

nitcorn :: http_response

Provides the HttpResponse class and http_status_codes
module i18n_phase

nitc :: i18n_phase

Basic support of internationalization through the generation of id-to-string tables
module ini

ini :: ini

Read and write INI configuration files
module inspect

serialization :: inspect

Refine Serializable::inspect to show more useful information
module iso8859_1

core :: iso8859_1

Codec for ISO8859-1 I/O
module json

json :: json

Read and write JSON formatted text using the standard serialization services
module json_commands

nitc :: json_commands

Translate command results to json
module json_model

nitc :: json_model

Make model entities Serializable.
module kernel

core :: kernel

Most basic classes and methods.
module lexer

nitc :: lexer

Lexer and its tokens.
module lexer_work

nitc :: lexer_work

Internal algorithm and data structures for the Nit lexer
module libevent

libevent :: libevent

Low-level wrapper around the libevent library to manage events on file descriptors
module list

core :: list

This module handle double linked lists
module literal

nitc :: literal

Parsing of literal values in the abstract syntax tree.
module loader

nitc :: loader

Loading of Nit source files
module local_var_init

nitc :: local_var_init

Verify that local variables are initialized before their usage
module location

nitc :: location

Nit source-file and locations in source-file
module logger

logger :: logger

A simple logger for Nit
module markdown

markdown :: markdown

Markdown parsing.
module math

core :: math

Mathematical operations
module md5

md5 :: md5

Native MD5 digest implementation as Text::md5
module md_commands

nitc :: md_commands

Render commands results as Markdown
module mdoc

nitc :: mdoc

Documentation of model entities
module media_types

nitcorn :: media_types

Services to identify Internet media types (or MIME types, Content-types)
module meta

meta :: meta

Simple user-defined meta-level to manipulate types of instances as object.
module mmodule

nitc :: mmodule

modules and module hierarchies in the metamodel
module mmodule_data

nitc :: mmodule_data

Define and retrieve data in modules
module model

nitc :: model

Classes, types and properties
module model_base

nitc :: model_base

The abstract concept of model and related common things
module model_collect

nitc :: model_collect

Collect things from the model.
module model_examples

nitc :: model_examples

Examples for Model entities
module model_index

nitc :: model_index

Search things from the Model
module modelbuilder_base

nitc :: modelbuilder_base

Load nit source files and build the associated model
module modelize

nitc :: modelize

Create a model from nit source files
module modelize_class

nitc :: modelize_class

Analysis and verification of class definitions to instantiate model element
module modelize_property

nitc :: modelize_property

Analysis and verification of property definitions to instantiate model element
module mongodb

mongodb :: mongodb

MongoDB Nit Driver.
module more_collections

more_collections :: more_collections

Highly specific, but useful, collections-related classes.
module mpackage

nitc :: mpackage

Modelisation of a Nit package
module native

core :: native

Native structures for text and bytes
module native_curl

curl :: native_curl

Binding of C libCurl which allow us to interact with network.
module native_mongodb

mongodb :: native_mongodb

Native wrapper for the MongoDB C Driver
module nitcorn

nitcorn :: nitcorn

The nitcorn Web server framework creates server-side Web apps in Nit
module nitpm_shared

nitc :: nitpm_shared

Services related to the Nit package manager
module no_warning

nitc :: no_warning

Fill toolcontext information about blacklisting of warnings.
module numeric

core :: numeric

Advanced services for Numeric types
module opts

opts :: opts

Management of options on the command line
module ordered_tree

ordered_tree :: ordered_tree

Manipulation and presentation of ordered trees.
module parallelization_phase

nitc :: parallelization_phase

Phase generating threads for functions annotated with threaded annotation
module parse_annotations

nitc :: parse_annotations

Simple annotation parsing
module parser

nitc :: parser

Parser.
module parser_base

parser_base :: parser_base

Simple base for hand-made parsers of all kinds
module parser_nodes

nitc :: parser_nodes

AST nodes of the Nit language
module parser_prod

nitc :: parser_prod

Production AST nodes full definition.
module parser_util

nitc :: parser_util

Utils and tools related to parsers and AST
module parser_work

nitc :: parser_work

Internal algorithm and data structures for the Nit parser
module phase

nitc :: phase

Phases of the processing of nit programs
module pipeline

pipeline :: pipeline

Pipelined filters and operations on iterators.
module pop_config

popcorn :: pop_config

Configuration file and options for Popcorn apps
module pop_handlers

popcorn :: pop_handlers

Route handlers.
module pop_json

popcorn :: pop_json

Introduce useful services for JSON REST API handlers.
module pop_repos

popcorn :: pop_repos

Repositories for data management.
module pop_routes

popcorn :: pop_routes

Internal routes representation.
module pop_sessions

popcorn :: pop_sessions

Session handlers
module pop_tasks

popcorn :: pop_tasks

Popcorn threaded tasks
module pop_validation

popcorn :: pop_validation

Quick and easy validation framework for Json inputs
module popcorn

popcorn :: popcorn

Application server abstraction on top of nitcorn.
module poset

poset :: poset

Pre order sets and partial order set (ie hierarchies)
module protocol

core :: protocol

module pthreads

pthreads :: pthreads

Main POSIX threads support and intro the classes Thread, Mutex and Barrier
module queries

mongodb :: queries

Mongo queries framework
module queue

core :: queue

Queuing data structures and wrappers
module range

core :: range

Module for range of discrete objects.
module rbtree

trees :: rbtree

A red–black tree is a data structure which is a type of self-balancing binary search tree.
module re

core :: re

Regular expression support for all services based on Pattern
module reactor

nitcorn :: reactor

Core of the nitcorn project, provides HttpFactory and Action
module realtime

realtime :: realtime

Services to keep time of the wall clock time
module regex_phase

nitc :: regex_phase

Check for error in regular expressions from string literals
module ropes

core :: ropes

Tree-based representation of a String.
module safe

serialization :: safe

Services for safer deserialization engines
module scope

nitc :: scope

Identification and scoping of local variables and labels.
module semantize

nitc :: semantize

Process bodies of methods in regard with the model.
module serialization

serialization :: serialization

General serialization services
module serialization_core

serialization :: serialization_core

Abstract services to serialize Nit objects to different formats
module serialization_model_phase

nitc :: serialization_model_phase

Phase generating methods (model-only) to serialize Nit objects
module serialization_read

json :: serialization_read

Services to read JSON: deserialize_json and JsonDeserializer
module serialization_write

json :: serialization_write

Services to write Nit objects to JSON strings: serialize_to_json and JsonSerializer
module server_config

nitcorn :: server_config

Classes and services to configure the server
module sessions

nitcorn :: sessions

Automated session management
module signal_handler

nitcorn :: signal_handler

Handle SIGINT and SIGTERM to close the server after all active events
module simple_misc_analysis

nitc :: simple_misc_analysis

Simple vavious processing on a AST
module sorter

core :: sorter

This module contains classes used to compare things and sorts arrays.
module static

json :: static

Static interface to read Nit objects from JSON strings
module store

json :: store

Store and load json data.
module stream

core :: stream

Input and output streams of characters
module tables

nitc :: tables

Module that interfaces the parsing tables.
module template

template :: template

Basic template system
module text

core :: text

All the classes and methods related to the manipulation of text entities
module time

core :: time

Management of time and dates
module token

nitcorn :: token

Simple generate_token service, independent of the rest of the nitcorn framework
module toolcontext

nitc :: toolcontext

Common command-line tool infrastructure than handle options and error messages
module trees

trees :: trees

General module for tree data structures
module trie

trees :: trie

A trie (or prefix tree) is a datastructure used to perform prefix searches.
module typing

nitc :: typing

Intraprocedural resolution of static types and OO-services
module uml

nitc :: uml

Group head module for UML generation services
module uml_base

nitc :: uml_base

Exposes the base class for UML generation of a Model
module uml_class

nitc :: uml_class

Provides facilities of exporting a Model to a UML class diagram
module uml_module

nitc :: uml_module

Services for generation of a UML package diagram based on a Model
module union_find

core :: union_find

union–find algorithm using an efficient disjoint-set data structure
module utf8

core :: utf8

Codec for UTF-8 I/O
module vararg_routes

nitcorn :: vararg_routes

Routes with parameters.
module version

nitc :: version

This file was generated by git-gen-version.sh

Parents

module api_base

nitc :: api_base

Base classes used by nitweb.
module pop_auth

popcorn :: pop_auth

Authentification handlers.

Children

module api

nitc :: api

Components required to build a web server about the nit model.

Descendants

module a_star-m

a_star-m

module nitweb

nitc :: nitweb

Runs a webserver based on nitcorn that render things from model.
# Feedback related features
module api_feedback

import api_base
import popcorn::pop_auth

redef class NitwebConfig

	# MongoDB collection used to store stars.
	var stars = new StarRatingRepo(db.collection("stars")) is lazy
end

redef class APIRouter

	redef init do
		super

		use("/feedback/grades/most", new APIStarsMost(config))
		use("/feedback/grades/best", new APIStarsBest(config))
		use("/feedback/grades/worst", new APIStarsWorst(config))
		use("/feedback/grades/users", new APIStarsUsers(config))

		use("/feedback/user/stars", new APIUserStars(config))

		use("/feedback/stars/:id", new APIStars(config))
		use("/feedback/stars/:id/dimension/:dimension", new APIStarsDimension(config))
	end
end

# Base handler for feedback features.
abstract class APIFeedBack
	super APIHandler

	# Get the user logged in or null if no session
	fun get_session_user(req: HttpRequest): nullable User do
		var session = req.session
		if session == null then return null
		return session.user
	end

	# Get the login of the session user or null if no session
	fun get_session_login(req: HttpRequest): nullable String do
		var user = get_session_user(req)
		if user == null then return null
		return user.login
	end
end

# Most rated entities
class APIStarsMost
	super APIFeedBack

	redef fun get(req, res) do
		res.api_json(req, new JsonArray.from(config.stars.most_rated))
	end
end

# Best rated entities
class APIStarsBest
	super APIFeedBack

	redef fun get(req, res) do
		res.api_json(req, new JsonArray.from(config.stars.best_rated))
	end
end

# Best rated entities
class APIStarsWorst
	super APIFeedBack

	redef fun get(req, res) do
		res.api_json(req, new JsonArray.from(config.stars.worst_rated))
	end
end

# Best rated entities
class APIStarsUsers
	super APIFeedBack

	redef fun get(req, res) do
		res.api_json(req, new JsonArray.from(config.stars.users_ratings))
	end
end

# Stars attributed to mentities by user
class APIUserStars
	super APIFeedBack

	redef fun get(req, res) do
		var user = get_session_user(req)
		if user == null then return
		res.api_json(req, new JsonArray.from(user.ratings(config)))
	end
end

# Stars attributed to mentities
class APIStars
	super APIFeedBack

	redef fun get(req, res) do
		var login = get_session_login(req)
		var mentity = mentity_from_uri(req, res)
		if mentity == null then return
		res.api_json(req, mentity.ratings(config, login))
	end
end

# Stars attributed to mentities by dimension
class APIStarsDimension
	super APIFeedBack

	redef fun get(req, res) do
		var login = get_session_login(req)
		var mentity = mentity_from_uri(req, res)
		if mentity == null then return
		var dimension = req.param("dimension")
		if dimension == null then return
		res.api_json(req, mentity.ratings_by_dimension(config, dimension, login))
	end

	redef fun post(req, res) do
		var user = get_session_user(req)
		var login = null
		if user != null then login = user.login

		var mentity = mentity_from_uri(req, res)
		if mentity == null then return
		var dimension = req.param("dimension")
		if dimension == null then return

		# Retrieve user previous rating
		var previous = null
		if user != null then
			previous = user.find_previous_rating(config, mentity, dimension)
		end

		var obj = req.body.parse_json
		if not obj isa JsonObject then
			res.api_error(400, "Expected a JSON object")
			return
		end
		var rating = obj["rating"]
		if not rating isa Int then
			res.api_error(400, "Expected a key `rating`")
			return
		end

		if previous != null then
			previous.rating = rating
			previous.timestamp = get_time
			config.stars.save previous
		else
			config.stars.save new StarRating(login, mentity.full_name, dimension, rating)
		end
		res.api_json(req, mentity.ratings_by_dimension(config, dimension, login))
	end
end

# Star ratings allow users to rate mentities with a 5-stars system.
#
# Each rating can consider only one `dimension` of the mentity.
# Dimensions are arbitrary strings used to group ratings.
class StarRating
	super RepoObject
	serialize

	# The user login that made that rating (or null if anon)
	var user: nullable String

	# Rated `MEntity::full_name`
	var mentity: String

	# The dimension rated (arbritrary key)
	var dimension: nullable String

	# The rating (traditionally a score between 0 and 5)
	var rating: Int is writable

	# Timestamp when this rating was created
	var timestamp = 0 is writable
end

redef class User

	# Find a previous rating of `self` for `mentity` and `dimension`
	fun find_previous_rating(config: NitwebConfig, mentity: MEntity, dimension: nullable String): nullable StarRating do
		var match = new MongoMatch
		match.eq("mentity", mentity.full_name)
		match.eq("dimension", dimension)
		match.eq("user", login)
		return config.stars.find(match)
	end

	# Find all ratings by `self`
	fun ratings(config: NitwebConfig): Array[StarRating] do
		return config.stars.find_all((new MongoMatch).eq("user", login))
	end
end

redef class MEntity

	# Get the ratings of a `dimension`
	fun ratings_by_dimension(config: NitwebConfig, dimension: String, user: nullable String): JsonObject do
		var match = (new MongoMatch).eq("mentity", full_name).eq("dimension", dimension)
		var pipeline = new MongoPipeline
		pipeline.match(match)
		pipeline.group((new MongoGroup("mean_group")).avg("mean", "$rating"))

		var res = config.stars.collection.aggregate(pipeline)
		var obj = new JsonObject
		obj["mean"] = if res.is_empty then 0.0 else res.first["mean"]
		obj["ratings"] = new JsonArray.from(config.stars.find_all(match))

		if user != null then
			match["user"] = user
			obj["user"] = config.stars.find(match)
		end
		return obj
	end

	# Get the ratings of a `mentity`
	fun ratings(config: NitwebConfig, user: nullable String): JsonObject do
		var match = new JsonObject
		match["mentity"] = full_name
		match["ratings"] = new JsonArray.from(config.stars.find_all(match))
		match["feature"] = ratings_by_dimension(config, "feature", user)
		match["doc"] = ratings_by_dimension(config, "doc", user)
		match["examples"] = ratings_by_dimension(config, "examples", user)
		match["code"] = ratings_by_dimension(config, "code", user)
		return match
	end
end

# StarRating Mongo Repository
class StarRatingRepo
	super MongoRepository[StarRating]

	# Find most rated mentities
	fun most_rated: Array[JsonObject] do
		var pipeline = new MongoPipeline
		pipeline.group((new MongoGroup("$mentity")).sum("count", 1))
		pipeline.sort((new MongoMatch).eq("count", -1))
		pipeline.limit(10)
		return collection.aggregate(pipeline)
	end

	# Find best rated mentities
	fun best_rated: Array[JsonObject] do
		var pipeline = new MongoPipeline
		pipeline.group((new MongoGroup("$mentity")).avg("avg", "$rating"))
		pipeline.sort((new MongoMatch).eq("avg", -1))
		pipeline.limit(10)
		return collection.aggregate(pipeline)
	end

	# Find worst rated mentities
	fun worst_rated: Array[JsonObject] do
		var pipeline = new MongoPipeline
		pipeline.group((new MongoGroup("$mentity")).avg("avg", "$rating"))
		pipeline.sort((new MongoMatch).eq("avg", 1))
		pipeline.limit(10)
		return collection.aggregate(pipeline)
	end

	# Find worst rated mentities
	fun users_ratings: Array[JsonObject] do
		var pipeline = new MongoPipeline
		pipeline.group((new MongoGroup("$user")).sum("count", 1))
		pipeline.sort((new MongoMatch).eq("count", -1))
		pipeline.limit(10)
		return collection.aggregate(pipeline)
	end
end

src/doc/api/api_feedback.nit:15,1--287,3