mirror of
https://github.com/mail-in-a-box/mailinabox.git
synced 2025-04-21 03:02:09 +00:00
Add files via upload
This commit is contained in:
parent
0335595e7e
commit
0a769f5b21
142
Documentation.txt
Normal file
142
Documentation.txt
Normal file
@ -0,0 +1,142 @@
|
||||
AudioGuardian v1.0 (Beta)
|
||||
Mobile Sound Notifier
|
||||
|
||||
Team Members
|
||||
Eric Hertz
|
||||
Brian Garfinkel
|
||||
Jeff Wang
|
||||
Torrey Umland
|
||||
Yin Lok Ho
|
||||
Mentor: Jeff Wilhelm
|
||||
|
||||
Description
|
||||
AudioGuardian is a mobile Java application (J2ME) for use on Java-enabled mobile phones. The user's phone
|
||||
|
||||
records surrounding noise and triggers alerts when it identifies interesting noises such as car horns, fire
|
||||
|
||||
alarms, gunshots, and sirens. This application was created for people who are hearing impaired and might have
|
||||
|
||||
difficulty knowing when they are in a dangerous situation. The project records emergency signals that people
|
||||
|
||||
take for granted and makes them available to those who are hearing impaired. It was created as a part of
|
||||
|
||||
Project:Possibility and SS12:UCLA 2009.
|
||||
|
||||
Challenges
|
||||
The application uses a discrete Fourier transform algorithm to convert a signal in the time domain into a
|
||||
|
||||
signal in the frequency domain. This distribution allows the application to identify specific sounds by
|
||||
|
||||
matching the measured frequency against a known sample frequency. The algorithm behind this was extremely
|
||||
|
||||
complicated to implement, because every microphone has a different DC offset. The application has a
|
||||
|
||||
calibration function that will allow the user to set the DC offset function for their specific microphone.
|
||||
|
||||
This alleviates any problems encountered by differences between hardware platforms. Porting Java to J2ME was
|
||||
|
||||
also difficult to implement. J2ME is not well documented on the Internet, so there was some difficulty in
|
||||
|
||||
learning how to program a mobile phone. There were some difficulties in processing the audio stream into a
|
||||
|
||||
byte array, since the application has to extract the sound data without having the file header in the stream
|
||||
|
||||
as well. The application has to remove the file header and then store the audio stream into a data structure,
|
||||
|
||||
otherwise the application will encounter some issues with displaying the graph of the Fourier transform. There
|
||||
|
||||
were also some challenges in using multithreading. The application runs in a loop that listens for commands.
|
||||
|
||||
However, the command thread cannot be interrupted to perform recording tasks. Thefore, the application has to
|
||||
|
||||
run any recording operations in a separate thread. There were some issues with integrating the separate
|
||||
|
||||
threads so that they worked in sync with one another.
|
||||
|
||||
Design
|
||||
This application is implemented in J2ME, which is a subset of Java specifically designed for mobile phones.
|
||||
|
||||
AAnalyzer class
|
||||
This class analyzes the amplitude of the sound file and returns the maximum amplitude at any point in the
|
||||
|
||||
sample file. It can also return the number of samples with levels above a given threshold value. It can get
|
||||
|
||||
the average amplitude of the entire sample.
|
||||
|
||||
AudioGuardian class
|
||||
This class is the driver class for the entire application. It implements a CommandListener that runs continually in a thread and executes commands as the user inputs them. It also creates new threads as needed for recording operations. It generates the GUI for the entire application and runs through the menus.
|
||||
|
||||
CAboutScreen class
|
||||
This class displays the credit screen using the Form super class.
|
||||
|
||||
Calibrator class
|
||||
This class reads in an arbitrary amount of sound data and takes the average of the amplitudes. It then
|
||||
|
||||
computes the base offset for the microphone. This is useful for the application since there are many
|
||||
|
||||
differences between different microphones. Without this, the graph would have no way to normalize itself.
|
||||
|
||||
CCalibrationScreen class
|
||||
This class displays the screen that the user sees while calibration is going on.
|
||||
|
||||
CMatchableSound class
|
||||
This class holds the attributes of the sounds that the application is trying to match. It has a method that
|
||||
|
||||
will perform matching between a given sound file and a recorded stream.
|
||||
|
||||
COptionScreen class
|
||||
This class displays the "Config" screen. It holds all the different settings that the user can select.
|
||||
|
||||
COptionDb class
|
||||
This class encapsulates the RecordStore and provides a much nicer interface for working with RecordStores.
|
||||
|
||||
CStartupScreen class
|
||||
This class displays the logo on start up.
|
||||
|
||||
DFT class
|
||||
This class performs the discrete Fourier transform. It returns an array of DFT pairs. Each DFT pair contains a
|
||||
|
||||
frequency and its corresponding amplitude (also known as a DFTpair).
|
||||
|
||||
DFTpair class (extends Comparable)
|
||||
This is the interface that defines what a DFT pair is.
|
||||
|
||||
Float11 class
|
||||
This is a math class that provides functions not present in the standard J2ME API.
|
||||
|
||||
FloorLevel class
|
||||
This class defines a Double object that is used to store the base microphone offset.
|
||||
|
||||
Graph class
|
||||
This class displays the waveform of the sound signal. It also displays a bar graph of the discrete Fourier
|
||||
|
||||
transform. It also provides functions to allow the user to find the highest level frequency and an assorted
|
||||
|
||||
array of frequencies based on the sound input.
|
||||
|
||||
Monitor class
|
||||
This class listens for sound input and stores that sound input into a DFT array. It sorts the sound file by
|
||||
|
||||
amplitude.
|
||||
|
||||
QuickSort class
|
||||
This class defines a QuickSort algorithm for use by the Monitor class.
|
||||
|
||||
Schedule of Progress
|
||||
Day One: Saturday, January 31, 2009
|
||||
8:30 AM: Arrive at Boelter and prepare for the project
|
||||
9:00 AM - 1 PM: Work on design and basic implementation
|
||||
1 PM - 1:30 PM: Eat lunch
|
||||
1:30 PM - 6 PM: Finish basic implementations and work on defining the discrete Fourier transform
|
||||
6 PM - 6:30 PM: Eat dinner
|
||||
6:30 PM - 11:59 PM: Work on advanced implementations and GUI
|
||||
|
||||
Day Two: Sunday, February 1, 2009
|
||||
12:00 AM - 3:45 AM: Preliminary integration, work on GUI, extension of the project
|
||||
3:45 AM: Walk back to dorms to sleep
|
||||
9:00 AM: Arrive at Boelter to continue work
|
||||
9:00 AM - 1 PM: Work on integration of the code, work on extending the scope of the project
|
||||
1 PM - 1:30 PM: Eat lunch
|
||||
1:30 PM - 6:00 PM: Finish integrating code, write documentation, prepare presentation and demo
|
||||
6:00 PM - 6:30 PM: Eat dinner
|
||||
6:30 PM - Close: Presentations and demonstrations
|
BIN
GIF image.gif
Normal file
BIN
GIF image.gif
Normal file
Binary file not shown.
After Width: | Height: | Size: 176 KiB |
138
LICENSE
138
LICENSE
@ -1,121 +1,29 @@
|
||||
Creative Commons Legal Code
|
||||
BSD 3-Clause License
|
||||
|
||||
CC0 1.0 Universal
|
||||
Copyright (c) 2018, Oscar Gomez
|
||||
All rights reserved.
|
||||
|
||||
CREATIVE COMMONS CORPORATION IS NOT A LAW FIRM AND DOES NOT PROVIDE
|
||||
LEGAL SERVICES. DISTRIBUTION OF THIS DOCUMENT DOES NOT CREATE AN
|
||||
ATTORNEY-CLIENT RELATIONSHIP. CREATIVE COMMONS PROVIDES THIS
|
||||
INFORMATION ON AN "AS-IS" BASIS. CREATIVE COMMONS MAKES NO WARRANTIES
|
||||
REGARDING THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS
|
||||
PROVIDED HEREUNDER, AND DISCLAIMS LIABILITY FOR DAMAGES RESULTING FROM
|
||||
THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS PROVIDED
|
||||
HEREUNDER.
|
||||
Redistribution and use in source and binary forms, with or without
|
||||
modification, are permitted provided that the following conditions are met:
|
||||
|
||||
Statement of Purpose
|
||||
* Redistributions of source code must retain the above copyright notice, this
|
||||
list of conditions and the following disclaimer.
|
||||
|
||||
The laws of most jurisdictions throughout the world automatically confer
|
||||
exclusive Copyright and Related Rights (defined below) upon the creator
|
||||
and subsequent owner(s) (each and all, an "owner") of an original work of
|
||||
authorship and/or a database (each, a "Work").
|
||||
* Redistributions in binary form must reproduce the above copyright notice,
|
||||
this list of conditions and the following disclaimer in the documentation
|
||||
and/or other materials provided with the distribution.
|
||||
|
||||
Certain owners wish to permanently relinquish those rights to a Work for
|
||||
the purpose of contributing to a commons of creative, cultural and
|
||||
scientific works ("Commons") that the public can reliably and without fear
|
||||
of later claims of infringement build upon, modify, incorporate in other
|
||||
works, reuse and redistribute as freely as possible in any form whatsoever
|
||||
and for any purposes, including without limitation commercial purposes.
|
||||
These owners may contribute to the Commons to promote the ideal of a free
|
||||
culture and the further production of creative, cultural and scientific
|
||||
works, or to gain reputation or greater distribution for their Work in
|
||||
part through the use and efforts of others.
|
||||
* Neither the name of the copyright holder nor the names of its
|
||||
contributors may be used to endorse or promote products derived from
|
||||
this software without specific prior written permission.
|
||||
|
||||
For these and/or other purposes and motivations, and without any
|
||||
expectation of additional consideration or compensation, the person
|
||||
associating CC0 with a Work (the "Affirmer"), to the extent that he or she
|
||||
is an owner of Copyright and Related Rights in the Work, voluntarily
|
||||
elects to apply CC0 to the Work and publicly distribute the Work under its
|
||||
terms, with knowledge of his or her Copyright and Related Rights in the
|
||||
Work and the meaning and intended legal effect of CC0 on those rights.
|
||||
|
||||
1. Copyright and Related Rights. A Work made available under CC0 may be
|
||||
protected by copyright and related or neighboring rights ("Copyright and
|
||||
Related Rights"). Copyright and Related Rights include, but are not
|
||||
limited to, the following:
|
||||
|
||||
i. the right to reproduce, adapt, distribute, perform, display,
|
||||
communicate, and translate a Work;
|
||||
ii. moral rights retained by the original author(s) and/or performer(s);
|
||||
iii. publicity and privacy rights pertaining to a person's image or
|
||||
likeness depicted in a Work;
|
||||
iv. rights protecting against unfair competition in regards to a Work,
|
||||
subject to the limitations in paragraph 4(a), below;
|
||||
v. rights protecting the extraction, dissemination, use and reuse of data
|
||||
in a Work;
|
||||
vi. database rights (such as those arising under Directive 96/9/EC of the
|
||||
European Parliament and of the Council of 11 March 1996 on the legal
|
||||
protection of databases, and under any national implementation
|
||||
thereof, including any amended or successor version of such
|
||||
directive); and
|
||||
vii. other similar, equivalent or corresponding rights throughout the
|
||||
world based on applicable law or treaty, and any national
|
||||
implementations thereof.
|
||||
|
||||
2. Waiver. To the greatest extent permitted by, but not in contravention
|
||||
of, applicable law, Affirmer hereby overtly, fully, permanently,
|
||||
irrevocably and unconditionally waives, abandons, and surrenders all of
|
||||
Affirmer's Copyright and Related Rights and associated claims and causes
|
||||
of action, whether now known or unknown (including existing as well as
|
||||
future claims and causes of action), in the Work (i) in all territories
|
||||
worldwide, (ii) for the maximum duration provided by applicable law or
|
||||
treaty (including future time extensions), (iii) in any current or future
|
||||
medium and for any number of copies, and (iv) for any purpose whatsoever,
|
||||
including without limitation commercial, advertising or promotional
|
||||
purposes (the "Waiver"). Affirmer makes the Waiver for the benefit of each
|
||||
member of the public at large and to the detriment of Affirmer's heirs and
|
||||
successors, fully intending that such Waiver shall not be subject to
|
||||
revocation, rescission, cancellation, termination, or any other legal or
|
||||
equitable action to disrupt the quiet enjoyment of the Work by the public
|
||||
as contemplated by Affirmer's express Statement of Purpose.
|
||||
|
||||
3. Public License Fallback. Should any part of the Waiver for any reason
|
||||
be judged legally invalid or ineffective under applicable law, then the
|
||||
Waiver shall be preserved to the maximum extent permitted taking into
|
||||
account Affirmer's express Statement of Purpose. In addition, to the
|
||||
extent the Waiver is so judged Affirmer hereby grants to each affected
|
||||
person a royalty-free, non transferable, non sublicensable, non exclusive,
|
||||
irrevocable and unconditional license to exercise Affirmer's Copyright and
|
||||
Related Rights in the Work (i) in all territories worldwide, (ii) for the
|
||||
maximum duration provided by applicable law or treaty (including future
|
||||
time extensions), (iii) in any current or future medium and for any number
|
||||
of copies, and (iv) for any purpose whatsoever, including without
|
||||
limitation commercial, advertising or promotional purposes (the
|
||||
"License"). The License shall be deemed effective as of the date CC0 was
|
||||
applied by Affirmer to the Work. Should any part of the License for any
|
||||
reason be judged legally invalid or ineffective under applicable law, such
|
||||
partial invalidity or ineffectiveness shall not invalidate the remainder
|
||||
of the License, and in such case Affirmer hereby affirms that he or she
|
||||
will not (i) exercise any of his or her remaining Copyright and Related
|
||||
Rights in the Work or (ii) assert any associated claims and causes of
|
||||
action with respect to the Work, in either case contrary to Affirmer's
|
||||
express Statement of Purpose.
|
||||
|
||||
4. Limitations and Disclaimers.
|
||||
|
||||
a. No trademark or patent rights held by Affirmer are waived, abandoned,
|
||||
surrendered, licensed or otherwise affected by this document.
|
||||
b. Affirmer offers the Work as-is and makes no representations or
|
||||
warranties of any kind concerning the Work, express, implied,
|
||||
statutory or otherwise, including without limitation warranties of
|
||||
title, merchantability, fitness for a particular purpose, non
|
||||
infringement, or the absence of latent or other defects, accuracy, or
|
||||
the present or absence of errors, whether or not discoverable, all to
|
||||
the greatest extent permissible under applicable law.
|
||||
c. Affirmer disclaims responsibility for clearing rights of other persons
|
||||
that may apply to the Work or any use thereof, including without
|
||||
limitation any person's Copyright and Related Rights in the Work.
|
||||
Further, Affirmer disclaims responsibility for obtaining any necessary
|
||||
consents, permissions or other rights required for any use of the
|
||||
Work.
|
||||
d. Affirmer understands and acknowledges that Creative Commons is not a
|
||||
party to this document and has no duty or obligation with respect to
|
||||
this CC0 or use of the Work.
|
||||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
|
||||
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
||||
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
||||
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
|
||||
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
|
||||
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
|
||||
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
||||
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
|
||||
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
|
BIN
PNG image 5.png
Normal file
BIN
PNG image 5.png
Normal file
Binary file not shown.
After Width: | Height: | Size: 98 KiB |
149
__init__.py
Normal file
149
__init__.py
Normal file
@ -0,0 +1,149 @@
|
||||
#!/usr/bin/env/python3
|
||||
# encoding: utf-8
|
||||
'''
|
||||
ripr -- shortdesc
|
||||
|
||||
ripr is a small app to record shoutcast or mp3 streams from the internet
|
||||
|
||||
It defines classes_and_methods
|
||||
|
||||
@author: Adam Garcia
|
||||
|
||||
@copyright: 2013 All rights reserved.
|
||||
|
||||
@license: MIT
|
||||
'''
|
||||
import sys
|
||||
import os
|
||||
import logging
|
||||
from urllib.request import urlretrieve
|
||||
from argparse import ArgumentParser
|
||||
from argparse import RawDescriptionHelpFormatter
|
||||
from datetime import date
|
||||
import time
|
||||
import signal
|
||||
import datetime
|
||||
import multiprocessing
|
||||
|
||||
|
||||
__all__ = []
|
||||
__version__ = 0.1
|
||||
__date__ = '2013-12-23'
|
||||
__updated__ = '2013-12-23'
|
||||
now = time.time()
|
||||
|
||||
DEBUG = 0
|
||||
TESTRUN = 0
|
||||
PROFILE = 0
|
||||
current_year = date.today().strftime("%Y")
|
||||
|
||||
|
||||
def signal_handler(signal, frame):
|
||||
print('You pressed Ctrl+C, quitting!')
|
||||
quit(0)
|
||||
signal.signal(signal.SIGINT, signal_handler)
|
||||
|
||||
|
||||
def get_seconds(s):
|
||||
l = s.split(':')
|
||||
return int(l[0]) * 3600 + int(l[1]) * 60 + int(l[2])
|
||||
|
||||
|
||||
def main(argv=None): # IGNORE:C0111
|
||||
'''Command line options.'''
|
||||
|
||||
if argv is None:
|
||||
argv = sys.argv
|
||||
else:
|
||||
sys.argv.extend(argv)
|
||||
|
||||
program_name = os.path.basename(sys.argv[0])
|
||||
program_version = "v%s" % __version__
|
||||
program_build_date = str(__updated__)
|
||||
program_version_message = '%%(prog)s %s (%s)' % (program_version,
|
||||
program_build_date)
|
||||
program_shortdesc = __import__('__main__').__doc__.split("\n")[1]
|
||||
program_license = '''%s
|
||||
|
||||
Created by ${user_name} on %s.
|
||||
Copyright ${year} ${organization_name}. All rights reserved.
|
||||
|
||||
The MIT License (MIT)
|
||||
|
||||
Copyright (c) <current_year> Adam Garcia
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
|
||||
|
||||
USAGE
|
||||
''' % (program_shortdesc, str(__date__))
|
||||
|
||||
# Setup argument parser
|
||||
parser = ArgumentParser(description=program_license,
|
||||
formatter_class=RawDescriptionHelpFormatter)
|
||||
parser.add_argument("-v", "--verbose",
|
||||
action="store_true",
|
||||
help="Turns on verbose logging")
|
||||
parser.add_argument(dest="url",
|
||||
help="""URL to record""", metavar="URL")
|
||||
parser.add_argument(dest="rec_time",
|
||||
help="""Duration to record in HH:MM:SS format""",
|
||||
metavar="HH:MM:SS")
|
||||
parser.add_argument("--path", "-p", dest='paths',
|
||||
help="""paths to folder(s) to record
|
||||
[default: %(default)s]""", metavar="PATH",
|
||||
nargs='?', default="output.mp3", const="blabla")
|
||||
args = parser.parse_args()
|
||||
paths = args.paths
|
||||
verbose = args.verbose
|
||||
rec_time = args.rec_time
|
||||
url = args.url
|
||||
time_limit = get_seconds(rec_time)
|
||||
def callback(count, blocksize, filesize):
|
||||
elapsed = time.time() - now
|
||||
if elapsed > time_limit:
|
||||
raise ValueError("The recording has elapsed past the set time")
|
||||
|
||||
try:
|
||||
urlretrieve(url, paths, callback)
|
||||
except ValueError as ve:
|
||||
print("Times up!")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
if DEBUG:
|
||||
sys.argv.append("-h")
|
||||
sys.argv.append("-v")
|
||||
sys.argv.append("-r")
|
||||
if TESTRUN:
|
||||
import doctest
|
||||
doctest.testmod()
|
||||
if PROFILE:
|
||||
import cProfile
|
||||
import pstats
|
||||
profile_filename = 'streamer.ripr_profile.txt'
|
||||
cProfile.run('main()', profile_filename)
|
||||
statsfile = open("profile_stats.txt", "wb")
|
||||
p = pstats.Stats(profile_filename, stream=statsfile)
|
||||
stats = p.strip_dirs().sort_stats('cumulative')
|
||||
stats.print_stats()
|
||||
statsfile.close()
|
||||
sys.exit(0)
|
||||
sys.exit(main())
|
BIN
animated-waffle-master.zip
Normal file
BIN
animated-waffle-master.zip
Normal file
Binary file not shown.
189
json-parser
Normal file
189
json-parser
Normal file
@ -0,0 +1,189 @@
|
||||
#!/usr/bin/env bash
|
||||
|
||||
function output_entry() {
|
||||
echo "$1=$2"
|
||||
}
|
||||
|
||||
function parse_array() {
|
||||
local current_path="${1:+$1.}$2"
|
||||
local current_scope="root"
|
||||
local current_index=0
|
||||
|
||||
while [ "$chars_read" -lt "$INPUT_LENGTH" ]; do
|
||||
[ "$preserve_current_char" == "0" ] && chars_read=$((chars_read+1)) && read -r -s -n 1 c
|
||||
preserve_current_char=0
|
||||
c=${c:-' '}
|
||||
|
||||
case "$current_scope" in
|
||||
"root") # Waiting for new object or value
|
||||
case "$c" in
|
||||
'{')
|
||||
parse_object "$current_path" "$current_index"
|
||||
current_scope="entry_separator"
|
||||
;;
|
||||
']')
|
||||
return
|
||||
;;
|
||||
[\"tfTF\-0-9])
|
||||
preserve_current_char=1 # Let the parse value function decide what kind of value this is
|
||||
parse_value "$current_path" "$current_index"
|
||||
preserve_current_char=1 # Parse value has terminated with a separator or an array end, but we can handle this only in the next while iteration
|
||||
current_scope="entry_separator"
|
||||
;;
|
||||
|
||||
esac
|
||||
;;
|
||||
"entry_separator")
|
||||
[ "$c" == "," ] && current_index=$((current_index+1)) && current_scope="root"
|
||||
[ "$c" == "]" ] && return
|
||||
;;
|
||||
esac
|
||||
done
|
||||
}
|
||||
|
||||
function parse_value() {
|
||||
local current_path="${1:+$1.}$2"
|
||||
local current_scope="root"
|
||||
|
||||
while [ "$chars_read" -lt "$INPUT_LENGTH" ]; do
|
||||
[ "$preserve_current_char" == "0" ] && chars_read=$((chars_read+1)) && read -r -s -n 1 c
|
||||
preserve_current_char=0
|
||||
c=${c:-' '}
|
||||
|
||||
case "$current_scope" in
|
||||
"root") # Waiting for new string, number or boolean
|
||||
case "$c" in
|
||||
'"') # String begin
|
||||
current_scope="string"
|
||||
current_varvalue=""
|
||||
;;
|
||||
[\-0-9]) # Number begin
|
||||
current_scope="number"
|
||||
current_varvalue="$c"
|
||||
;;
|
||||
[tfTF]) # True or false begin
|
||||
current_scope="boolean"
|
||||
current_varvalue="$c"
|
||||
;;
|
||||
"[") # Array begin
|
||||
parse_array "" "$current_path"
|
||||
return
|
||||
;;
|
||||
"{") # Object begin
|
||||
parse_object "" "$current_path"
|
||||
return
|
||||
esac
|
||||
;;
|
||||
"string") # Waiting for string end
|
||||
case "$c" in
|
||||
'"') # String end if not in escape mode, normal character otherwise
|
||||
[ "$current_escaping" == "0" ] && output_entry "$current_path" "$current_varvalue" && return
|
||||
[ "$current_escaping" == "1" ] && current_varvalue="$current_varvalue$c" && current_escaping=0
|
||||
;;
|
||||
'\') # Escape character, entering or leaving escape mode
|
||||
current_escaping=$((1-current_escaping))
|
||||
current_varvalue="$current_varvalue$c"
|
||||
;;
|
||||
*) # Any other string character
|
||||
current_escaping=0
|
||||
current_varvalue="$current_varvalue$c"
|
||||
;;
|
||||
esac
|
||||
;;
|
||||
"number") # Waiting for number end
|
||||
case "$c" in
|
||||
[,\]}]) # Separator or array end or object end
|
||||
output_entry "$current_path" "$current_varvalue"
|
||||
preserve_current_char=1 # The caller needs to handle this char
|
||||
return
|
||||
;;
|
||||
[\-0-9.]) # Number can only contain digits, dots and a sign
|
||||
current_varvalue="$current_varvalue$c"
|
||||
;;
|
||||
# Ignore everything else
|
||||
esac
|
||||
;;
|
||||
"boolean") # Waiting for boolean to end
|
||||
case "$c" in
|
||||
[,\]}]) # Separator or array end or object end
|
||||
output_entry "$current_path" "$current_varvalue"
|
||||
preserve_current_char=1 # The caller needs to handle this char
|
||||
return
|
||||
;;
|
||||
[a-zA-Z]) # No need to do some strict checking, we do not want to validate the incoming json data
|
||||
current_varvalue="$current_varvalue$c"
|
||||
;;
|
||||
# Ignore everything else
|
||||
esac
|
||||
;;
|
||||
esac
|
||||
done
|
||||
}
|
||||
|
||||
function parse_object() {
|
||||
local current_path="${1:+$1.}$2"
|
||||
local current_scope="root"
|
||||
|
||||
while [ "$chars_read" -lt "$INPUT_LENGTH" ]; do
|
||||
[ "$preserve_current_char" == "0" ] && chars_read=$((chars_read+1)) && read -r -s -n 1 c
|
||||
preserve_current_char=0
|
||||
c=${c:-' '}
|
||||
|
||||
case "$current_scope" in
|
||||
"root") # Waiting for new field or object end
|
||||
[ "$c" == "}" ] && return
|
||||
[ "$c" == "\"" ] && current_scope="varname" && current_varname="" && current_escaping=0
|
||||
;;
|
||||
"varname") # Reading the field name
|
||||
case "$c" in
|
||||
'"') # String end if not in escape mode, normal character otherwise
|
||||
[ "$current_escaping" == "0" ] && current_scope="key_value_separator"
|
||||
[ "$current_escaping" == "1" ] && current_varname="$current_varname$c"
|
||||
;;
|
||||
'\') # Escape character, entering or leaving escape mode
|
||||
current_escaping=$((1-current_escaping))
|
||||
current_varname="$current_varname$c"
|
||||
;;
|
||||
*) # Any other string character
|
||||
current_escaping=0
|
||||
current_varname="$current_varname$c"
|
||||
;;
|
||||
esac
|
||||
;;
|
||||
"key_value_separator") # Waiting for the key value separator (:)
|
||||
[ "$c" == ":" ] && parse_value "$current_path" "$current_varname" && current_scope="field_separator"
|
||||
;;
|
||||
"field_separator") # Waiting for the field separator (,)
|
||||
[ "$c" == ',' ] && current_scope="root"
|
||||
[ "$c" == '}' ] && return
|
||||
;;
|
||||
esac
|
||||
done
|
||||
}
|
||||
|
||||
function parse() {
|
||||
chars_read=0
|
||||
preserve_current_char=0
|
||||
|
||||
while [ "$chars_read" -lt "$INPUT_LENGTH" ]; do
|
||||
read -r -s -n 1 c
|
||||
c=${c:-' '}
|
||||
chars_read=$((chars_read+1))
|
||||
|
||||
# A valid JSON string consists of exactly one object
|
||||
[ "$c" == "{" ] && parse_object "" "" && return
|
||||
# ... or one array
|
||||
[ "$c" == "[" ] && parse_array "" "" && return
|
||||
|
||||
done
|
||||
}
|
||||
|
||||
if [ -z "$@" ]; then
|
||||
INPUT=$(cat -)
|
||||
else
|
||||
INPUT=$(echo "$@")
|
||||
fi
|
||||
|
||||
INPUT_LENGTH="${#INPUT}"
|
||||
parse "" "" <<< "${INPUT}"
|
||||
|
Loading…
Reference in New Issue
Block a user