Compare commits

...

9 Commits

@ -1,3 +1,136 @@
# appstore
# Backendless search and website generator from activity bundles prototype
App store for Python 3 activities
## Instruction to use
Steps:
1. Clone or download & extract this app store repository
2. run main.py script in generator folder as:
```
$ python3 main.py "/bundles/directory" "/website/template/root/directory/"
```
All sub-directories of bundles directory will be scanned for activity
bundles i.e. .xo files.
**WARNING:** for now website template has symblink of search.html as index.html. I do not know if it works in Windows OS. If not, delete index.html and copy search.html as index.html.
**WARNING 2**: error log files and info.json file will be saved in website root directory for now. delete them if not needed.
**WARNING3:** In prototype, paths are written in Unix style so likely won't work on Windows. This will be corrected after some time. For now, you can replace '/' with '\'. Also, I do not think (unsure) current directory is represented as './' (or even '.\') in Windows. So maybe remove that as well.
## Issues
### What should be the license for the project?
I am OK with any FSF approved license which is suitable for Sugarlabs needs.
### Should there be fallback backend when js is disabled in browser for search functionality to work?
## To-DO
- [x] Create search function js file, JSON data file & html page stitching them together
- [ ] NOTE: how will I ensure that results are presented in some order when more than one search result is of equal standing in term of keywords match/ranking etc. Popularity/download counts or newest/last updated?
- [ ] Python script to automatically add all apps to app store, generate html pages and append entry to JSON search index file.
- [x] Create demo website
- [ ] Add copyright & license information
- [ ] For production version, compress index.json file. Also use compressed version of jquery.
- [ ] in parent directory of website write a script to start static file server serving website sub-directory. This will be used when not using web server such as Nginx or Apache for acting as backend eg. a user can start server from usb stick.
- [x] in live website, a link to download entire website (as pre generated zip file?)
## Design choices
### Relative path of files instead of absolute
Since app store can be started just by opening index.html or any other html file in browser rather than first starting a server (even simple localhost one), keeping paths relative have advantage over absolute as they won't break and work even when any html file is opened directly in browser. One caveat will be that moving file from one directory to another will break its references. Script generating static pages need to keep this in mind i.e. must calculate references dynamically rather than hard coding them.
### CORS considerations
Since apptore is supposed to work even without starting a static file serving server i.e. by opening absolutely any HTML file in app store website directory, only way I found that nowadays browsers allow file to be loaded is when it's included by the HTML file opened itself. Files cannot be dynamically loaded later. This rules out all ajax calls in design of app store.
Thankfully, we can ask browser to defer loading of some files and wait for those files (search index) to be loaded. Instead of setting a asynchronous sleeping counter to check if search index is loaded, it's better if search index itself tell that it has loaded and we than perform any search in queue.
Credit: sphinx-doc code.
### jQuery framework
jQuery library is used as its lightweight and reduce a lot of code footprint (making project easy to maintain). Its more than enough as per our project requirement.
## Code guide
*Tip: if you don't have many activity bundles to test with than [download](https://github.com/tony37/Sugaractivities/archive/master.zip) or [clone](https://github.com/tony37/Sugaractivities.git) Tony's repo. It contains many (outdated) bundles in /activities directory.*
/generator/main.py (written as generator below) uses /website template to build website in /website directory.
generator takes two arguments
1. directory of bundles - Directory and all sub-directories are recursively scanned for .xo files
2. directory of website template - website will be generated in this directory
### Generator
/generator directory contains main.py file and GeneralFunctions directory which contains portable code which are not specific to this app store and are written in a way that they can be used in any program.
#### main.py
- starts from main() function (called only if main.py directly executed and not if imported as module)
##### main()
- processArguments() function is called which builds dictionary of program directory, (activity) bundles directory and website (template) directory from arguments given to generator.
- **extractData** is the main function which extract all the data from bundles and writes it to website directory.
##### extractData class
*Tip: all the functions in extractData function are sorted in alphabetical order*
- __init__() declares all object variables and call methods in order of operation
- self.createDirectories() - create directories used in website directory (if not already present) such as app, bundles, icons, js. Aborts program if fails to create directories eg. if no write permission.
- self.findBundles() - find all activity bundles i.e. .xo files in website directory and stores in self.activityBundles list
- self.purgeBundlesNotZipFile() - test with python standard library method zipfile.is_zipfile() and removes bundles which fails this test from self.activityBundles list
- self.extractInfoAndIconFromBundles() :
- reads activity.info files in bundles (skips bundles in which find no or more than one activity.info files)
- create variables dictionary from extracted information and appends dictionary to self.bundlesInfoList
- Looks for icon variables in dictionary and extracts icon file (skips if fails but continue processing that bundle as icon is not critical).
- copies bundle to website/directory/bundles
- self.generateInfoJson() - converts self.bundlesInfoList to json format and stores it in self.infoJson variable
- self.generateIndex() :
- extracts name, summary, description, tag, tags, category, categories from self.infoJson and stores in self.indexDictList in dictionary format and self.indexJs in json (string) format.
- Since several variables in selfinfoJson can map to one variable in index eg. tag, tags, category, categories all considered tags in index. Therefore, we first check if key already exist in index, if not than add, else append to data of existing value in dictionary.
- tuple and list are both considered same and treated same i.e. comma separated. while string is space separated.
- For all keys which are not added to dictionaries in the above process, empty entry is added. Eg. if summary is not written in activty.info file, than empty summary is ultimately added to index.json rather than no entry at all.
- **NOTE:** self.indexJs is js file string rather than json file. Its contains just a function call search.assignIndex([index json]) . (search is a class in search.js file in website-templates/js/ directory.
- self.generateAppsHtmlPages() - generates html pages from self.indexDictList and simultaneously saves rather than storing in memory.
- self.writeFiles() - info.json, index.js errors....txt files are written to files.
### Website template
- index.html - symblink to search.html for now
- search.html - search page
- /js/search.js - contains search class and general (portable) code which serves the search requests
- similarString() - case/*base* insensitive comparison of strings eg. 'A' == 'a' == 'à'.
- countSimilarWordsInStrings() - split words and do word by word comparison and count how many are similar by calling similarString()
- partialStrMatch() - Wok-in-progress function. intend is to match eg. 'car' == 'cars' and return .75 as 75% string match. This can possibly be tweaked to also include matches when typing error and suggest closest relevant word based on proportion/percentage match.
- search class - implements search functionality
- search.init() - called when page completes loading
- checks if any search query. if yes,
- fills search query back into search box ($('input[name="q"]')[0].value = query;)
- calls this.performSearch() withs earch query
- assignIndex() - this is the function called from index.js
- stores index in this._index variable
- checks if any query in queue and call this.performSearch is so. Queries can be in queue if this._index was not loaded by that time and searched now when the index is loaded.
- performSearch() - checks if index has loaded. calls processSearch() with query if so, else add query to queue.
- processSearch() - this function calls rankApps() to rank apps (in index) based on their match with query and displays 10 (for now) matched apps by calling displayResults()
- rankApps() - calls rankApp() to rank each app against query and stores in [rank, app index in this_index] array.
- rankApp() - calls countSimilarWordsInStrings() and rewards 10 points for match in name, 3 in summary, 2 in description and 5 in tags.
- displayResults() - unhides #searchResults div in search.html and presents search results or no search result found message.
- appObjToHtml() - generates html to present for matches apps. use index.json as source for generating.

@ -0,0 +1,120 @@
from sys import platform as OperatingSystem
Quotes = '"\''
if OperatingSystem == "win32":
PathSlash = '\\'
else:
PathSlash = '/'
FileProtocol = "file:" + 2*PathSlash
def ConvertToStandardPathFormat(Path):
""" Example,
Input: '"file:///some/path/somefile.extension"
Output: /some/path/somefile.extension
"""
Path = Path.strip(Quotes)
if Path.startswith(FileProtocol):
Path = Path[len(FileProtocol):]
return Path
def GetTextAfter(Text, ReadlinesTextFile):
for Lines in range(len(ReadlinesTextFile)):
Line = ReadlinesTextFile[Lines].strip('\n')
if Line.startswith(Text):
return Line[len(Text):]
return ''
def SingleQuoteString(String):
if len(String) > 0:
if String[0] != '\'' or String[-1] != '\'':
String = '\'' + String + '\''
return String
def DoubleQuoteString(String):
if len(String) > 0:
if String[0] != '"' or String[-1] != '"':
String = '"' + String + '"'
return String
def ListIntoString(List, QuoteItems=0, Seprator=' '):
if QuoteItems == 2:
for i in range(len(List)):
Quoteditem = DoubleQuoteString(List[i])
List[i] = Quoteditem
elif QuoteItems == 1:
for i in range(len(List)):
Quoteditem = SingleQuoteString(List[i])
List[i] = Quoteditem
Stringoflist = (Seprator).join(List)
return Stringoflist
# strip=0 => remove both ' & ", 1 => remove ', 2 => remove "
def UnquoteString(String, strip=0):
while True:
if (
strip != 2 and
String.startswith('"') and
String.endswith('"')
):
String = String.strip('"')
elif (
strip != 1
and String.startswith("'")
and String.endswith("'")
):
String = String.strip("'")
else:
break
return String
def StandardVariableName(Variable):
Variable = Variable.casefold()
Variable = Variable.replace('_', '').replace(' ', '')
return Variable
"""
def DictionaryToJsonStr(Dict, BaseIndentation=0):
BI = '\t'*BaseIndentation
JsonStr = BI+'{\n'
for k, v in Dict.items():
JsonStr += BI+'\t"'+k+'" : "'+v+'",\n'
JsonStr = JsonStr[:-2]
JsonStr += '\n'+BI+'}'
return JsonStr
"""
def StringToKeyValuePair(String, Seprator):
SepratorAt = String.find(Seprator)
if SepratorAt >= 0:
Key = String[:SepratorAt]
Value = String[SepratorAt+1:]
return Key, Value
else:
return "", String
def FormatStrForDictinary(String):
String = String.strip(" \n\r")
return UnquoteString(String)
def StrListToDictionary(
List,
Seprator='=',
FormatFunction=FormatStrForDictinary
):
Dictionary = {}
for i in List:
k, v = StringToKeyValuePair(i, Seprator)
k, v = FormatFunction(k), FormatFunction(v)
if len(k) > 0:
Dictionary[k] = v
return Dictionary

@ -0,0 +1,33 @@
from os.path import isfile as DoesFileExist
from .DataStructureManupulations import ConvertToStandardPathFormat
def ReadTextFile(FilePath):
FilePath = ConvertToStandardPathFormat(FilePath)
if DoesFileExist(FilePath) is True:
File = open(FilePath)
ReadFile = File.read()
File.close()
return ReadFile
else:
return ''
def ReadlinesTextFile(FilePath):
String = ReadTextFile(FilePath)
return String.split('\n')
def WriteTextFiles(FilePath, Text):
if type(Text) != str:
Text = '\n'.join(Text)
File = open(FilePath, 'w')
File.write(Text)
File.close()
def WriteBinaryToFile(Filepath, Data):
File = open(Filepath, 'wb')
File.write(Data)
File.close()

@ -0,0 +1,8 @@
import ssl
from urllib.request import urlopen
HttpsContext = ssl.create_default_context()
def Download(Url):
return urlopen(Url, context=HttpsContext).read()

@ -0,0 +1,18 @@
import os
def CallFuncInDir(Directory, Function, *args, **kwArgs):
CurrentDir = os.getcwd()
os.chdir(Directory)
Function(*args, **kwArgs)
os.chdir(CurrentDir)
# return True if operation succesful and False if failed
def CreateDir(Directory):
if not os.path.isfile(Directory):
if not os.path.isdir(Directory):
os.mkdir(Directory)
return True
else:
return False

@ -0,0 +1,304 @@
#!/usr/bin/python3
""" Run as:
python3 thisscript.py "/bundles/directoty" "/website/template/root/directory/
All sub-directories of bundles directory will be scanned for activity
bundles i.e. .xo files.
"""
import glob
import json
import os
import shutil
import sys
from urllib.parse import quote as strToHtmlFmt
import zipfile
from GeneralFunctions.DataStructureManupulations import (
StrListToDictionary
)
from GeneralFunctions.InputOutput import (
WriteTextFiles,
WriteBinaryToFile
)
from GeneralFunctions.OS import CreateDir
""" FIXME: paths hard coded unix style & most likely will not work on winodws.
Use code written for IMM to handle it.
"""
class extractData:
def findInfoFiles(self, bundle):
infoFiles = []
for File in bundle.namelist():
if File.endswith("activity/activity.info"):
infoFiles.append(File)
return infoFiles
def copyBundle(self, bundleSrc, activityName):
shutil.copy2(
bundleSrc,
self.websiteDir+"bundles/"+activityName+".xo"
)
def createDirectories(self):
assert(CreateDir(self.websiteDir+"app"))
assert(CreateDir(self.websiteDir+"icons"))
assert(CreateDir(self.websiteDir+"bundles"))
assert(CreateDir(self.websiteDir+"js"))
def extractActivityInfo(self, infoFilePath, zipFile):
infoList = []
infoList = zipFile.read(
infoFilePath).decode("utf-8").split('\n')
return StrListToDictionary(infoList)
def extractInfoAndIconFromBundles(self):
for bundlePath in self.activityBundles:
bundle = zipfile.ZipFile(bundlePath, "r")
infoFiles = self.findInfoFiles(bundle)
if len(infoFiles) != 1:
self.bundlesNotExactlyOneInfoFile.append(bundlePath)
else:
infoDict = self.extractActivityInfo(infoFiles[0], bundle)
self.bundlesInfoList.append(infoDict)
# FIXME: create seprate function for it
# extract and copy icon
activityName = infoDict.get("name")
if type(activityName) == str:
iconRelativePath = infoDict.get("icon")
if type(iconRelativePath) == str:
iconFolder = infoFiles[0][:infoFiles[0].rfind("/")+1]
iconAbsolutePath = (
iconFolder+iconRelativePath+".svg")
if iconAbsolutePath in bundle.namelist():
icon = bundle.read(iconAbsolutePath)
iconPath = (
self.websiteDir+"icons/" +
activityName
+ ".svg"
)
WriteBinaryToFile(iconPath, icon)
else:
# Conitnue without icon since non-fatal error
self.iconErroredBundles.append(bundlePath)
bundle.close()
# FIXME: uncomment below function.
# Disabled sometime during devlopment as time consuming
self.copyBundle(bundlePath, activityName)
bundle.close()
def findBundles(self):
self.activityBundles = glob.glob(
self.bundlesDir+"**/*.xo",
recursive=True
)
def generateAppsHtmlPages(self):
iconsDir = "../icons/"
bundlesDir = "../bundles/"
for appInfo in self.indexDictList:
pathName = strToHtmlFmt(appInfo["name"], safe='')
html = (
'<!DOCTYPE html>\n<html>\n<head>\n<title>' + appInfo["name"] +
'</title>\n<meta charset="utf-8"/>\n<link rel="stylesheet" '
'type="text/css" href="../css/main.css"/>\n</head>\n<body>\n'
'</body>\n<h1>' + appInfo["name"] + '</h1>\n<p><img src="' +
str(iconsDir + pathName + '.svg') + '"></img></p>\n'
'<div id=summary><h2>Summary</h2>\n<p>' + appInfo["summary"] +
'</p>\n</div>\n<div id=description><h2>Description</h2>\n<p>' +
appInfo["description"] + '</p>\n</div>\n<div id=tags><h2>Tags'
'</h2>\n<ul>\n'
)
for tag in appInfo["tags"]:
html += '<li>' + tag + '</li>\n'
html += (
'</ul>\n</div>\n<a href="' +
str(bundlesDir + pathName + '.xo') +
'"><h2>Download<h2></a>\n</body>\n</html>'
)
WriteTextFiles(
self.websiteDir+"./app/" + appInfo["name"] + ".html",
html
)
""" Only those which are specified in map will be added to index.
If an entry or value does not exist in infoJSON than emprty entry will
be created for it.
appends keys rather than replacing where mutiple map to same
"""
def generateIndex(
self,
infoToIndexMap={
"name": ("name", str),
"summary": ("summary", str),
"description": ("description", str),
"tag": ("tags", list),
"tags": ("tags", list),
"categories": ("tags", list),
"category": ("tags", list)
}
):
unexpectedInputError = (
"main.py generateIndex() : expect only str, list or tuple as "
"kwargs -> value[1] but found "
)
i2IMap = infoToIndexMap
for obj in json.loads(self.infoJson):
indexDict = {}
for k, v in obj.items():
if k in i2IMap:
# add new entry/key to app index
if k not in indexDict:
if i2IMap[k][1] == str:
indexDict[i2IMap[k][0]] = v
elif (i2IMap[k][1] == list
or i2IMap[k][1] == tuple):
if v.find(';') >= 0:
indexDict[i2IMap[k][0]] = v.split(';')
else:
indexDict[i2IMap[k][0]] = v.split()
# Append to existing entry/key to app index
else:
if i2IMap[k][1] == str:
indexDict[i2IMap[k][0]] += ' '+v
elif (i2IMap[k][1] == list
or i2IMap[k][1] == tuple):
if v.find(';') >= 0:
indexDict[i2IMap[k][0]] += v.split(';')
else:
indexDict[i2IMap[k][0]] += v.split()
else:
print(unexpectedInputError, i2IMap[k][1])
sys.exit(1)
# Create entry/key with empty value for keys not present
# in activty.info
for k, v in i2IMap.items():
if v[0] not in indexDict:
if v[1] == str:
indexDict[v[0]] = ""
elif (v[1] == list or v[1] == tuple):
indexDict[v[0]] = ()
else:
print(unexpectedInputError, v[1])
sys.exit(1)
self.indexDictList.append(indexDict)
self.indexJs = (
"search.assignIndex(" +
json.dumps(self.indexDictList, indent=4) +
")"
)
def generateInfoJson(self):
self.infoJson = json.dumps(self.bundlesInfoList, indent=4)
def __init__(self, bundlesDir, websiteDir):
""" FIXME: WARNING:: some files may be missing such as some app
may not have icon (use a placeholder icon for them)
Some bundles are not succesfully processed (html page + bundle copy)
but are not in error logs as well. There are 495 bundles in
Tony's repo, 479 sucessfully processed but showing fatal error of
12 only, i.e. 4 missing.
"""
self.bundlesDir = bundlesDir
self.websiteDir = websiteDir
self.activityBundles = []
self.bundlesNotZipFiles = []
self.bundlesNotExactlyOneInfoFile = []
self.bundlesInfoList = []
self.infoJson = ''
self.indexDictList = []
self.erroredBundles = []
self.iconErroredBundles = []
self.createDirectories()
self.findBundles()
self.purgeBundlesNotZipFile()
self.extractInfoAndIconFromBundles()
self.generateInfoJson()
self.generateIndex()
self.generateAppsHtmlPages()
self.writeFiles()
#self.copyBundles()
def purgeBundlesNotZipFile(self):
activityBundles = []
for bundle in self.activityBundles:
if zipfile.is_zipfile(bundle):
activityBundles.append(bundle)
else:
self.bundlesNotZipFiles.append(bundle)
self.activityBundles = activityBundles
def writeFiles(self):
""" Files which are not continously written during the process
Eg. Html, icon and bundles are written while processing each bundle
"""
WriteTextFiles(self.websiteDir+"info.json", self.infoJson)
WriteTextFiles(self.websiteDir+"js/index.js", self.indexJs)
WriteTextFiles(
self.websiteDir+"bundlesNotExactlyOneInfoFile.txt",
self.bundlesNotExactlyOneInfoFile
)
WriteTextFiles(
self.websiteDir+"bundlesNotZipFiles.txt",
self.bundlesNotZipFiles
)
WriteTextFiles(
self.websiteDir+"erroredBundles.txt",
self.erroredBundles
)
WriteTextFiles(
self.websiteDir+"iconErroredBundles.txt",
self.iconErroredBundles
)
def processArguments():
variables = {}
if len(sys.argv) == 3:
variables["programDir"] = os.path.dirname(
os.path.realpath(sys.argv[0]))+'/'
variables["bundlesDir"] = os.path.realpath(sys.argv[1])+'/'
variables["websiteDir"] = os.path.realpath(sys.argv[2])+'/'
else:
print(
"Please give exactly two arguments to program.\n"
"1. root directory of all activity bundles to be included "
"in website\n"
"2. root directory of website template\n"
)
sys.exit(1)
return variables
def main():
variables = processArguments()
extractData(variables["bundlesDir"], variables["websiteDir"])
if __name__ == "__main__":
main()

@ -0,0 +1,199 @@
@font-face {
font-family: "Quicksand-Regular";
/* license: url("../fonts/Quicksand-Regular.txt"); */
src: url("../fonts/Quicksand-Regular.ttf");
}
body {
/* background-color: #f4ffac4d; */
background-color: #fcfcfc;
color: #00386c;
font-family: Quicksand-Regular, roboto, sans-serif, monospace;
font-size: 1.2rem;
line-height: 1.5;
margin: 0 auto;
max-width: 900px;
text-align: justify;
}
header {
align-items: center;
border-bottom: 0.15rem solid #470598;
margin-bottom: 2rem;
margin-top: 2rem;
padding-bottom: 1rem
}
#Heading {
color: #099800; /*#00301fb3*/
font-size: 250%;
padding: 1rem;
text-align: center;
}
#Heading a {
color: #bfa800;
text-decoration: underline ;
}
#Heading a:hover {
color: #057e53 ;
}
h1 {
clear: both;
color: Crimson ;
font-weight: normal;
line-height: 1;
margin-bottom: -0.25rem;
text-align: center;
}
#color1 {
color: #0c007e;
}
#color1 a:hover {
color: DarkGoldenRod;
}
#color2 {
color: Crimson;
}
#color2 a:hover {
color: #9fbd06;
}
#color3 {
color: ForestGreen;
}
#color3 a:hover {
color: Teal;
}
#color4 {
color: DarkGoldenRod;
}
#color4 a:hover {
color: #4f08a7;
}
#color5 {
color: #90006b;
}
#color5 a:hover {
color: #08966e;
}
h2 {
color: #0c007e;
font-size: 175%;
font-weight: normal;
line-height: 1;
margin-bottom: -0.25rem;
}
h3 {
color: DarkGoldenRod;
font-size: 150%;
font-weight: normal;
line-height: 1;
margin-bottom: -0.25rem;
}
h4 {
color: SeaGreen;
font-size: 125%;
font-weight: normal;
line-height: 1;
margin-bottom: -0.25rem;
}
h5 {
color: Teal;
font-size: 100%;
font-weight: bold;
margin-bottom: -0.25rem;
}
h6 {
color: ForestGreen ;
font-size: 100%;
font-weight: normal;
}
#Date {
color: #0b8f73;
margin-bottom: -1rem;
}
p {
color: #260000;
}
p a {
color: #90006b;
}
a {
color: inherit;
}
a:hover {
color: #057e53 ;
}
img {
background-color: Teal;
display: block; /*required for aligning image to center*/
margin: auto; /*align image to center*/
max-width: 100%;
}
hr {
color: teal;
}
footer {
border-top: 0.15rem solid #f60000;
font-size: 85%;
line-height: 1.5;
margin-top: 2.5rem;
text-align: center;
}
footer a {
color: #400090;
}
#app_search {
margin: auto;
text-align: center;
padding: 20px;
}
/*=========================================*/
@media only screen and (min-width:10in) and (orientation:landscape) {
body {
/* margin: 0 5% 0 5%; */
}
}
@media only screen and (max-width:1000px) {
body {
margin: 0 2% 0 2%;
text-align: left;
}
}
@media only screen and (orientation:portrait) {
body {
text-align: left;
}
}

@ -0,0 +1,93 @@
Copyright 2011 The Quicksand Project Authors (https://github.com/andrew-paglinawan/QuicksandFamily), with Reserved Font Name “Quicksand”.
This Font Software is licensed under the SIL Open Font License, Version 1.1.
This license is copied below, and is also available with a FAQ at:
http://scripts.sil.org/OFL
-----------------------------------------------------------
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
-----------------------------------------------------------
PREAMBLE
The goals of the Open Font License (OFL) are to stimulate worldwide
development of collaborative font projects, to support the font creation
efforts of academic and linguistic communities, and to provide a free and
open framework in which fonts may be shared and improved in partnership
with others.
The OFL allows the licensed fonts to be used, studied, modified and
redistributed freely as long as they are not sold by themselves. The
fonts, including any derivative works, can be bundled, embedded,
redistributed and/or sold with any software provided that any reserved
names are not used by derivative works. The fonts and derivatives,
however, cannot be released under any other type of license. The
requirement for fonts to remain under this license does not apply
to any document created using the fonts or their derivatives.
DEFINITIONS
"Font Software" refers to the set of files released by the Copyright
Holder(s) under this license and clearly marked as such. This may
include source files, build scripts and documentation.
"Reserved Font Name" refers to any names specified as such after the
copyright statement(s).
"Original Version" refers to the collection of Font Software components as
distributed by the Copyright Holder(s).
"Modified Version" refers to any derivative made by adding to, deleting,
or substituting -- in part or in whole -- any of the components of the
Original Version, by changing formats or by porting the Font Software to a
new environment.
"Author" refers to any designer, engineer, programmer, technical
writer or other person who contributed to the Font Software.
PERMISSION & CONDITIONS
Permission is hereby granted, free of charge, to any person obtaining
a copy of the Font Software, to use, study, copy, merge, embed, modify,
redistribute, and sell modified and unmodified copies of the Font
Software, subject to the following conditions:
1) Neither the Font Software nor any of its individual components,
in Original or Modified Versions, may be sold by itself.
2) Original or Modified Versions of the Font Software may be bundled,
redistributed and/or sold with any software, provided that each copy
contains the above copyright notice and this license. These can be
included either as stand-alone text files, human-readable headers or
in the appropriate machine-readable metadata fields within text or
binary files as long as those fields can be easily viewed by the user.
3) No Modified Version of the Font Software may use the Reserved Font
Name(s) unless explicit written permission is granted by the corresponding
Copyright Holder. This restriction only applies to the primary font name as
presented to the users.
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
Software shall not be used to promote, endorse or advertise any
Modified Version, except to acknowledge the contribution(s) of the
Copyright Holder(s) and the Author(s) or with their explicit written
permission.
5) The Font Software, modified or unmodified, in part or in whole,
must be distributed entirely under this license, and must not be
distributed under any other license. The requirement for fonts to
remain under this license does not apply to any document created
using the Font Software.
TERMINATION
This license becomes null and void if any of the above conditions are
not met.
DISCLAIMER
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
OTHER DEALINGS IN THE FONT SOFTWARE.

@ -0,0 +1 @@
search.html

10872
website/js/jquery.js vendored

File diff suppressed because it is too large Load Diff

@ -0,0 +1,160 @@
"use strict";
var similarString = function(a, b) {
return !a.localeCompare(b, undefined, {sensitivity: 'base'});
}
var countSimilarWordsInStrings = function(str1, str2) {
var count = 0;
var array1 = str1.split(' ');
var array2 = str2.split(' ');
for (var wordX of array1) {
for (var wordY of array2) {
if (similarString(wordX, wordY))
count++;
}
}
return count;
}
// FIXME: function not yet tested
var partialStrMatch = function(str1, str2) {
var lengthDiff = str1.length - str2.length;
if (lengthDiff < 0) {
[str1, str2] = [str2, str1];
lengthDiff = -lengthDiff;
}
for (var i=0; i <= lengthDiff; i++) {
var str1Part = str1.substr(i, i+lengthDiff);
if (similarString(str1Part, str2))
return 1;
}
return 0;
}
var search = {
_index : null,
_queuedQuery : null,
appObjToHtml : function(app) {
var html = '<hr><h1><a href="./app/'+app.name+'.html">'+app.name+'</a></h1>\n<p><img src="./icons/'+app.name+'.svg" style="max-width: 250px"></img></p>\n<div id=summary><h2>Summary</h2>\n<p>'+app.summary+'</p>\n</div>\n<div id=description><h2>Description</h2>\n<p>'+app.description+'</p>\n</div>\n<div id=tags><h2>Tags</h2>\n<ul>\n';
for (var tag of app.tags)
html += '<li>'+ tag +'</li>\n';
html += '</ul>\n</div>\n';
return html;
},
assignIndex : function(index) {
this._index = index;
if (this._queuedQuery !== null) {
var queuedQuery = this._queuedQuery;
this._queuedQuery = null;
performSearch(queuedQuery);
}
},
displayResults : function(results) {
$("#searchResults").show();
if (results[0][0] <= 0) {
$(".sR:eq(1)").html("<h1>No search result found</h1>");
return;
}
for (var i=0; i <= $(".sR").length; i++) {
// No more entries matching query
if (results[i][0] <= 0)
break
var app = this._index[results[i][1]];
var html = this.appObjToHtml(app);
$(".sR:eq("+i+")").html(html);
}
},
getQueryParameters : function (queryString) {
var queryString = document.location.search;
return this.parseQueryParameters(queryString);
},
indexLoaded : function () {
return (this._index !== null);
},
init : function () {
var params = this.getQueryParameters();
if (params.q) {
var query = params.q[0];
query = query.replace("+", " ");
$('input[name="q"]')[0].value = query;
this.performSearch(query);
}
},
parseQueryParameters : function (queryString) {
var parameters = {}
var parts = queryString.substr(queryString.indexOf('?')+1).split('&');
for (var pair of parts) {
var spliter = pair.indexOf('=');
var key = pair.substr(0, spliter);
var value = pair.substr(spliter+1);
if (key in parameters)
parameters[key].push(value);
else
parameters[key] = [value];
}
return parameters;
},
performSearch : function (query) {
if (this.indexLoaded())
this.processSearch(query);
else
this._queuedQuery = query;
},
processSearch : function (query) {
var results = this.rankApps(query);
results.sort(function(a, b) {
// sort in descending rank order
return b[0]-a[0];
});
this.displayResults(results);
},
rankApp : function(app, query) {
var rank = 0;
rank += 10*countSimilarWordsInStrings(app.name, query);
// rank += partialStrMatch(app.name, query);
rank += 3*countSimilarWordsInStrings(app.summary, query);
// rank += partialStrMatch(app.summary, query);
rank += 2*countSimilarWordsInStrings(app.description, query);
// rank += partialStrMatch(app.description, query);
for (var tag of app.tags)
rank += 5*countSimilarWordsInStrings(tag, query);
// below statement causes error: tag is undefined when empty?
// rank += partialStrMatch(tag, query);
return rank;
},
rankApps : function(query) {
var results = [];
for (var i=0; i < this._index.length; i++) {
var app = this._index[i];
var rank = this.rankApp(app, query);
results.push([rank, i]);
}
return results;
}
};
$(document).ready( function() {
search.init();
});

@ -0,0 +1,75 @@
<!DOCTYPE html>
<html>
<head>
<title>Sugar Activites App Store Search Prototype</title>
<meta charset="utf-8"/>
<link rel="stylesheet" type="text/css" href="./css/main.css"/>
<script type="application/javascript" src="./js/jquery.js"></script>
<script type="application/javascript" src="./js/search.js"></script>
<script type="application/javascript" src="./js/index.js" defer></script>
<!-- <script type="application/json" src="./index.json" defer></script> -->
</head>
<body>
<div id=searchBar>
<form action="" method="GET" id=app_search>
<input
type=text
placeholder="Search Activities"
name="q"
id="search_box"
/>
<input
type="submit"
value="Search"
id="search_button"
/>
</form>
</div>
<div id=searchResults style="display:none">
<p class=sR>
<div class=appName>
</div>
</p>
<p class=sR>
<div class=appName>
</div>
</p>
<p class=sR>
<div class=appName>
</div>
</p>
<p class=sR>
<div class=appName>
</div>
</p>
<p class=sR>
<div class=appName>
</div>
</p>
<p class=sR>
<div class=appName>
</div>
</p>
<p class=sR>
<div class=appName>
</div>
</p>
<p class=sR>
<div class=appName>
</div>
</p>
<p class=sR>
<div class=appName>
</div>
</p>
<p class=sR>
<div class=appName>
</div>
</p>
</div>
</body>
</html>
Loading…
Cancel
Save