"E-Commerece Web Application": Master of Computer Applications
"E-Commerece Web Application": Master of Computer Applications
"E-Commerece Web Application": Master of Computer Applications
Project Report
On
By
BIKASH PRADHAN(22PG030331)
BIPIN KUMAR BHADRA(22PG0303332)
BIBHULI KUMAR BHOLA SAHOO(22PG030346)
SCHOOL OF SCIENCES
A Project submitted
in partial fulfilment of the requirements
for the Degree of
By
BIKASH PRADHAN
REGISTRATION NO
22PG030331
22PG0303332
22PG030
2023-2024
GIET UNIVERSITY,GUNUPUR
Department of Computer Science & Applications
Dist. - Rayagada, Odisha-765022
CERTIFICATE
We express our sincere gratitude to Prof. Satya Narayan Das, Head of The Department of
Computer Science and Applications for allowing me to accomplish the project. With his
active support and guidance, this project report has been completed.
We also thank Mr. Ashutosh Mallik our Project Coordinator for guidance and help.
We also thank Mrs. Sucheta Krupalini Moharana our Project Supervisor for guidance and help.
Page Number
Abstract 1
1. Introduction 2-4
1.1 Purpose 2
1.2 Project Scope 2
1.3 Project Features 3-4
2. Literature Review 5-7
3. Problem Statement 8-10
4. System Analysis 11-33
4.1 Identification of Need 11
4.2 Preliminary Investigation 12-13
4.3 Feasibility Study 13 -14
4.4 Project Planning 15-17
4.5 Software Requirement Specifications (SRS) 17-31
4.6 Software Engineering Paradigm Applied 31-33
5. System Design &Specifications 34-47
5.1 Data models (like DFD) 41-43
5.2 Entity Relationship Model 44
5.3 Use-case Diagrams 44-45
5.4 Class Diagrams 45-46
5.5 State Diagrams/Sequence Diagrams 47
6. Source Code 48-88
7. Screenshots 89-92
8. Testing 93-100
8.1 Testing Techniques and Testing Strategies Used Testing Plan used 94-96
8.2 Test Reports for Unit Test Cases and System Test Cases 96-100
9. Conclusion 101-102
10. Future Enhancement 103-105
11. References / Bibliography 106
ABSTRACT
Title: Development of an E-STORE Using Python, D jango, HTML, CSS, and Bootstrap
Abstract:
In today's digital age, online shopping has become increasingly popular, especially for
essential items like groceries. This project aims to develop a comprehensive online
grocery shop using Python, Django, HTML, CSS, and Bootstrap.
The system will provide users with a convenient platform to browse through a wide
range of grocery products, add them to their cart, and securely complete their purchases.
The backend will be powered by Django, a high-level Python web framework, which
will handle user authentication, product management, order processing, and database
interactions.
The frontend will be developed using HTML, CSS, and Bootstrap to create a visually
appealing and responsive user interface. Bootstrap's grid system and components will
ensure that the website is accessible across various devices and screen sizes, providing a
seamless shopping experience for users on desktops, laptops, tablets, and smartphones.
Key features of the online grocery shop will include user registration and login, product
categorization and search functionality, product details and images, shopping cart
management, secure payment processing integration, order tracking, and email
notifications.
Overall, this project aims to leverage modern web development technologies to create
an efficient and user-friendly online grocery shopping platform, catering to the needs of
today's digitally savvy consumers.
1
INTRODUCTION
PURPOSE :
2
PROJECT FEATURES :
Here's a breakdown of the project features for the online grocery shop developed using Python,
Django, HTML, CSS, and Bootstrap:
1. User Registration and Authentication:
- Allow users to register with the platform by providing necessary details.
- Implement authentication mechanisms to ensure secure access to user accounts.
- Enable users to log in and log out of their accounts securely.
2. Product Management:
- Provide functionality for administrators to add, edit, and delete grocery products.
- Include fields such as product name, description, price, quantity, and images.
- Implement product categorization and tagging for easy navigation.
3. Browsing and Searching:
- Enable users to browse through the available grocery products conveniently.
- Implement search functionality to allow users to find specific products quickly.
- Provide filtering options based on categories, prices, and other attributes.
4. Shopping Cart Management:
- Allow users to add products to their shopping carts while browsing.
- Provide options to update the quantity or remove items from the cart.
- Display the total cost and summary of items in the shopping cart.
5. Checkout Process:
- Implement a streamlined checkout process for users to complete their purchases.
- Include forms for users to provide shipping and billing information.
- Integrate secure payment gateways for processing transactions (e.g., PayPal, Stripe).
3
1.1.1 Error Handling and Security: Robust error handling mechanisms and security
measures are implemented to ensure data integrity, user privacy, and protection against
unauthorized access.
4
1. LITERATURE REVIEW
Collaborative music playback systems have emerged as a novel way for users to engage with
music in shared listening experiences. These systems enable multiple users to synchronize
their music playback across devices, allowing for collaborative playlist creation, voting on
tracks, and real-time interaction. This literature review aims to provide a comprehensive
overview of existing research and developments in collaborative music playback systems,
focusing on design principles, technical implementations, user experiences, and the social
impact of these systems.
Looking ahead, future research directions in collaborative music playback systems may
include exploring novel interaction paradigms, integrating emerging technologies like virtual
reality and spatial audio, and investigating the social and cultural implications of shared
6
listening experiences. Moreover, interdisciplinary collaborations between researchers,
designers, musicians, and industry stakeholders can lead to innovative solutions that redefine
how people discover, share, and enjoy music together in the digital age.
7
2. PROBLEM STATEMENT
The problem statement for the project revolves around the need for a collaborative music
playback system that allows multiple users to join a virtual room, synchronize playback, and
control music playback together. Existing music streaming platforms lack real-time
collaboration features, limiting the ability for users to enjoy music together simultaneously.
Therefore, there is a need to develop a platform that enables users to create and join rooms,
interact with other users in real-time, and collectively control music playback. This project
aims to address these limitations by implementing features such as room creation, user
authentication through Spotify, real-time synchronization of playback, and control of
playback features by both hosts and guests.
3.1.2 User Authentication and Integration with Spotify API: Integrating user
authentication via Spotify and leveraging the Spotify API to retrieve and control music
playback requires handling OAuth flows securely and managing access tokens effectively.
3.1.3 Room Management and Data Consistency: Managing rooms dynamically, including
creation, joining, and leaving, while maintaining data consistency and integrity across
connected users presents challenges in database design and synchronization.
3.1.4 Playback Control Permissions: Implementing logic to allow hosts to control playback
permissions for guests, such as play, pause, and skip, requires robust authorization
mechanisms.
3.1.5 Real-Time Updates and Notifications: Enabling real-time updates for playback
control and room settings poses challenges in handling WebSocket communications and
ensuring efficient event propagation.
8
3.1.6 Error Handling and Resilience: Implementing robust error handling mechanisms to
address potential failures in API calls, user authentication, or real-time synchronization is
essential for maintaining a seamless user experience.
• Utilize efficient data structures and algorithms for managing playback state and
ensuring synchronized playback experiences.
• Implement OAuth 2.0 authentication flow securely to authenticate users with their
Spotify accounts.
• Utilize Spotify API endpoints to retrieve user-specific music data, control playback,
and manage user permissions.
• Design a robust database schema to manage rooms, users, and playback state
efficiently.
• Implement role-based access control (RBAC) mechanisms to manage user roles (host
vs. guest) and permissions for controlling playback.
9
3.2.5 Real-Time Updates and Notifications
• Implement robust error handling mechanisms to gracefully handle errors and failures
in API calls, authentication flows, and real-time communication.
• Utilize logging and monitoring tools to track and diagnose errors in real-time,
ensuring quick resolution and minimal disruption to the user experience.
10
3. SYSTEM ANALYSIS
• With the increasing popularity of music streaming services like Spotify, there's a
growing demand for collaborative music playback systems that allow users to listen
to music together in real-time.
• Many users enjoy listening to music with friends or family members, whether they're
in the same location or miles apart. A collaborative music playback system fulfills
the need for shared music listening experiences.
• With the rise of virtual events and gatherings, there's a need for platforms that enable
participants to listen to music together during online parties, virtual hangouts, or
remote celebrations.
• In remote work and learning environments, collaborative music playback systems can
serve as icebreakers, team-building tools, or background entertainment during
virtual meetings and study sessions.
• Users often have diverse musical preferences and tastes. A collaborative music
playback system allows users to share and discover music based on their individual
preferences, creating personalized listening experiences.
11
4.2 PRELIMINARY INVESTIGATION:
The preliminary investigation of this project involves cconducting initial research and
analysis to gather information and assess the feasibility of the project. It includes the
following steps:
• Clarify the project's goals and objectives, such as developing a collaborative music
playback system, integrating with the Spotify API, enabling real-time
synchronization of playback, and providing user-friendly interfaces.
• Assess the technical feasibility of implementing the project, considering factors such
as available resources (e.g., technology stack, development tools), integration with
third-party APIs (e.g., Spotify), and scalability requirements.
• Determine the resources needed for the project, including personnel, time, budget,
hardware, and software. Allocate resources effectively to ensure successful project
execution.
12
4.2.7 Risk Assessment
• Identify potential risks and challenges associated with the project, such as technical
complexities, data security concerns, regulatory compliance, and dependencies on
external factors (e.g., API changes).
• Evaluate the costs and benefits of implementing the project, considering factors such
as development costs, potential revenue streams, market demand, competitive
advantage, and long-term sustainability.
• Assess the technical requirements of integrating with the Spotify API and
implementing real-time synchronization of playback across multiple users.
• Evaluate the compatibility of chosen technologies (Python, Django, React) with the
project requirements.
• Compare the projected costs with the budget allocated for the project to ensure
financial viability.
13
4.3.3 Operational Feasibility
• Evaluate the operational aspects of the project, including how it will be managed,
maintained, and supported post-launch.
• Assess the availability of skilled personnel to develop, deploy, and maintain the
application.
• Consider scalability requirements and whether the project can accommodate growth
in user base and usage over time.
• Identify any legal or regulatory requirements related to music streaming, user data
privacy, copyright, and licensing.
• Ensure compliance with relevant laws and regulations to avoid legal issues and
penalties.
• Analyze the market demand for collaborative music playback systems and the
potential user base for the application.
• Determine if the project fills a gap in the market and offers unique features or
advantages compared to existing solutions.
• Consider any dependencies, constraints, or risks that may impact the project schedule.
• Ensure that the proposed timeline aligns with stakeholders' expectations and business
objectives.
14
4.4 PROJECT PLANNING
Project planning for this collaborative music playback system involves organizing tasks,
allocating resources, and establishing timelines to ensure successful development and
deployment. Here's an outline of the project planning process:
• Clearly articulate the goals and objectives of the project, including the features and
functionality of the collaborative music playback system.
• Break down the project into smaller, manageable tasks and subtasks.
• Estimate the time required to complete each task based on factors such as complexity,
dependencies, and available resources.
• Create a project timeline or Gantt chart that outlines the sequence of tasks, milestones,
and deadlines.
• Identify potential risks and uncertainties that may impact the project schedule, budget,
or quality.
• Develop strategies to mitigate risks and minimize their impact on the project.
15
• Establish contingency plans to address unforeseen challenges that may arise during
development.
• Assign roles and responsibilities to team members based on their skills, expertise, and
availability.
• Regularly monitor project progress against the established schedule and milestones.
• Track resource utilization, budget expenditures, and any deviations from the plan.
• Implement corrective actions as needed to keep the project on track and address any
issues or delays.
• Solicit feedback and address any concerns to ensure stakeholder satisfaction and
alignment with project goals.
• Conduct a post-project review to assess the overall success of the collaborative music
playback system. Evaluate the project against its original objectives, budget, and
schedule.
16
• Prepare a formal project closure report summarizing the project's outcomes,
achievements, and recommendations for future improvements.
4.5.1 Introduction
• User Management
• Music Playback
• Users can play, pause, skip, and control playback of music tracks.
• Real-time Synchronization
• Music playback is synchronized across all connected users in the same room.
• Voting System
• Users can vote to skip tracks, with the option for hosts to set the minimum
number of votes required.
17
• Room Management
• Hosts can close the room, preventing new participants from joining.
• User Interaction
• Users can chat with other participants in the same room, enhancing social
interaction.
• Playback History
• The system maintains a playback history for each room, allowing users to
view previously played tracks and their associated metadata.
• Guest Permissions
• Playlist Management
• Users can create and manage playlists within the application, adding or
removing tracks from their personal collection.
• Hosts can create shared playlists for the entire room to collaborate on.
• Performance
• Security
• Reliability
• Usability
• It should provide feedback and guidance to users as they interact with the
system.
• Accessibility
• Scalability
• The system should adhere to data privacy regulations such as GDPR (General
Data Protection Regulation).
19
• User consent mechanisms should be implemented for data collection and
processing activities.
• Logs should be generated for system events, user actions, and error conditions,
aiding in troubleshooting and auditing.
Spotify API
• Integration with the Spotify API for music playback and user authentication.
Frontend Interface
Database Interface
• Interaction with the database to store user information, room settings, and playback
data.
4.5.5 Constraints
Technology Stack
➢ Front-End Development
HTML, or Hypertext Markup Language, is the standard language used to create and
design web pages. It provides the structure for web content by using various tags and
attributes to define elements on a page. HTML is the backbone of web development,
providing the foundation for creating visually appealing and interactive web pages. It
works hand in hand with CSS (Cascading Style Sheets) for styling and JavaScript for
interactivity, forming the core technologies of the World Wide Web.
20
Overview of HTML
▪ Tags: HTML is built on tags, which are enclosed in angle brackets `< >`. Tags
are used to define different types of content on a webpage, such as headings,
paragraphs, images, links, and more.
▪ Elements: HTML elements are made up of tags and the content they surround.
For example, a paragraph element `<p>` starts with an opening tag and ends with
a closing tag `</p>`, enclosing the paragraph text.
▪ Attributes: Tags can have attributes that provide additional information about an
element. Attributes are placed within the opening tag and typically come inname-
value pairs, such as `href` in an anchor tag `<a href="https://example.com">`.
▪ HTML: The HTML element (`<html>`) is the root element of an HTML page. It
wraps all the content on the page.
▪ Head: The head element (`<head>`) contains metadata and links to external
resources used by the HTML document. It doesn't display any content directly to
the user.
▪ Meta: The meta element (`<meta>`) is used to provide metadata about the HTML
document. Common uses include specifying the character encoding (`charset`
attribute) and setting the viewport for responsive design (`viewport` attribute).
21
▪ Title: The title element (`<title>`) sets the title of the HTML document, which is
displayed in the browser's title bar or tab. It's also used by search engines for page
indexing and in bookmarks.
▪ Div: The div element (`<div>`) is a generic container used to group and style
HTML elements. It's often used to create sections or divisions within a webpage
and is styled using CSS.
▪ Body: The body element (`<body>`) contains the content of the HTML document
that's displayed to the user. It includes text, images, links, forms, and other
elements that make up the visible part of the webpage.
CSS (Cascading Style Sheets) is a language used for describing the presentation
of a document written in HTML (HyperText Markup Language). Here's an overview
of CSS:
▪ Selectors: CSS selectors are patterns used to select the elements you want to
style. They can select elements based on their tag name, class, ID, attributes, and
more. They are a fundamental part of CSS syntax and play a crucial role in
styling web pages.
▪ Properties and Values: CSS properties are the styling attributes you can apply to
selected elements. Each property has a specific value associated with it that
defines how the property should be applied. Examples of properties include
`color`, `font-size`, `background-color`, `margin`, `padding`, and `border`.
▪ Cascading: CSS stands for "Cascading" Style Sheets, which refers to the way
styles are applied to elements. Styles can be inherited from parent elements,
overridden by more specific selectors, or overwritten by inline styles.
▪ Units: CSS supports different units of measurement for specifying sizes and
distances, such as pixels (`px`), percentages (`%`), ems (`em`), rems (`rem`), and
viewport units (`vw`, `vh`, `vmin`, `vmax`).
22
❖ JavaScript
JavaScript (JS) serves as the primary language for adding interactivity and
dynamic behavior to web pages. Here's an overview of JavaScript within the
project context:
23
▪ Animation and Effects: JavaScript can create animations and visual effects on
web pages using techniques like CSS animations, transitions, and
libraries/frameworks such as jQuery or GSAP (GreenSock Animation
Platform).
❖ React
React is a JavaScript library used for building user interfaces, particularly for
single-page applications (SPAs) where content is dynamically updated without
requiring full page reloads. Here's an overview of React within this project:
24
▪ JSX (JavaScript XML): React utilizes JSX, a syntax extension that allows
developers to write HTML-like code within JavaScript. JSX makes it
easier to describe UI components and their structure, combining HTML
markup with JavaScript logic seamlessly.
▪ Props (Properties): React components can receive data via props, which
are essentially read-only inputs passed from parent to child components.
Props allow for communication between components and enable
component customization and reusability.
25
▪ Component Libraries and Ecosystem: React has a rich ecosystem of third-
party libraries and tools that extend its capabilities. This includes state
management libraries like Redux, UI component libraries like Material-UI
or Ant Design, and development tools like React DevTools and Create
React App.
➢ Back-End Development
❖ Python
Python serves as the backend language, responsible for handling server-side logic,
database interactions, and API endpoints. Python serves as the backend language,
responsible for handling server-side logic, database interactions, and API
endpoints.
▪ Django Framework: The project likely uses the Django web framework, which
is a high-level Python web framework that encourages rapid development and
clean, pragmatic design. Django provides a set of built-in tools and
conventions for handling common web development tasks, such as URL
routing, database modeling, and user authentication.
▪ API Endpoints: Python code defines API endpoints using Django's `django-
rest-framework` or similar libraries. These endpoints handle incoming HTTP
requests from the frontend, perform necessary data processing or database
operations, and return appropriate HTTP responses (usually in JSON format)
containing the requested data or indicating the outcome of the request.
❖ Django
Django serves as the web framework for building the backend of the application.
Django provides a comprehensive set of tools and conventions for building web
applications quickly and efficiently. Its batteries-included approach, robust security
features, and thriving ecosystem of third-party packages make it a popular choice
for building scalable and maintainable web applications.
27
views handle the logic to process requests and generate responses, and
templates are used for rendering HTML pages.
▪ URL Routing: Django's URL dispatcher maps URL patterns to view functions
or classes, allowing developers to define how different URLs should be
handled by the application. URL patterns are typically defined in the project's
`urls.py` file and may include regular expressions or path converters to capture
dynamic parts of the URL.
▪ Forms and Validation: Django provides a forms library for handling HTML
forms and form data. Forms can be created using Python classes, and Django
handles tasks such as form rendering, data validation, and error handling
automatically. Forms can be used in views to process user input and interact
with the database.
28
Authorization can be enforced using decorators or middleware to restrict
access to certain views or resources.
▪ Static Files and Media Handling: Django provides utilities for managing static
files (e.g., CSS, JavaScript) and media files (e.g., user-uploaded images,
videos). Static files are typically served directly by the web server in
production, while media files are stored locally or on a cloud storage service
like Amazon S3.
➢ API
❖ Spotify API:
29
access token, which is used to make authenticated requests to the Spotify API
on behalf of the user.
▪ Authorization Code Flow: The application uses the authorization code flow to
authenticate users with Spotify. This flow involves redirecting the user to the
Spotify authorization page with specific parameters, including the client ID,
redirect URI, and requested scopes (permissions). After the user grants
permission, Spotify redirects back to the application with an authorization
code, which is exchanged for an access token and refresh token.
▪ Error Handling and Edge Cases: The application handles potential errors and
edge cases that may arise during interactions with the Spotify API. This
includes scenarios such as invalid access tokens, expired tokens, rate limiting,
and network errors. Error handling mechanisms ensure that the application
provides a smooth and reliable user experience even in the face of API-related
issues.
30
Scalability:
4.5.6 Appendices
Include any additional information relevant to the software requirements, such as use
case diagrams, data flow diagrams, or mockups.
31
4.6.1 Iterative Development: The project can be broken down into smaller increments or
iterations, allowing for continuous improvement and feedback throughout the development
process. Features can be implemented incrementally, with regular demonstrations to
stakeholders for feedback and validation.
4.6.4 Customer-Centric Focus: Agile places a strong emphasis on delivering value to the
customer. In this project, the customer-centric focus means prioritizing features and
functionalities that align with user needs and preferences, ensuring a positive user experience.
4.6.6 Sprint Planning: The project team conducts regular sprint planning meetings to
prioritize tasks and set goals for each iteration. This ensures that development efforts are
focused on delivering the most valuable features incrementally.
4.6.7 Daily Stand-ups: Daily stand-up meetings are held to provide a forum for team
members to discuss progress, identify any impediments, and coordinate their efforts. These
short, focused meetings help maintain alignment and address any issues promptly.
4.6.8 Iterative Feedback: Agile encourages continuous feedback loops, both from
stakeholders and end-users. Regular demos and reviews allow stakeholders to provide
feedback on the product's features and functionality, facilitating early course correction and
improvement.
32
4.6.9 Empowered Teams: Agile principles promote self-organizing, empowered teams that
take ownership of their work. Team members have the autonomy to make decisions and
adapt to changing requirements, fostering a sense of accountability and commitment to
project success.
4.6.11 Adaptive Planning: Agile methodologies recognize that requirements and priorities
may evolve over time. The project plan remains flexible, allowing for adjustments based on
feedback, changes in market conditions, or emerging opportunities.
33
4. SYSTEM DESIGN AND SPECIFICATIONS
The system design and specifications for this project outline the architecture, components,
and functionality of the collaborative music playback system. Here's an overview:
❖ Architecture:
The system follows a client-server architecture, where the server hosts the backend
logic and data storage, while the client interacts with the user through a web-based
interface.
Backend components include Django framework for server-side logic, Spotify API
integration for music playback functionality, and a PostgreSQL database for storing
user data and room information.
Frontend components utilize React.js for building interactive user interfaces and
managing state.
❖ Components:
Backend Components:
• PostgreSQL database for storing user profiles, room details, playback history, and
voting data.
Frontend Components:
• React.js for building modular UI components, managing state, and handling user
interactions.
• Material-UI library for designing responsive and visually appealing user interfaces.
• React Router for client-side routing to navigate between different views within the
application.
34
❖ Functionality:
User Authentication: Users can log in to the system using their Spotify accounts to
access the collaborative music playback features.
Room Management: Hosts can create a room and generate a unique code that other
users can use to join the room. Hosts can also set room preferences such as playback
control permissions and voting requirements.
Music Playback: Users can play, pause, skip tracks, and adjust playback volume
within the room. Playback control permissions are determined by the host's settings.
Voting System: Users can vote to skip tracks, and tracks are skipped when the
required number of votes is reached.
Real-time Updates: Hosts can update playback control settings and voting
requirements in real-time, reflecting changes immediately for all users in the room.
❖ Specifications:
System supports concurrent user sessions with efficient handling of authentication and
session management.
Integration with Spotify API ensures seamless access to music catalogs, playback
control, and user authentication.
Data storage and retrieval operations are optimized for performance and scalability,
ensuring smooth operation even under high user loads.
35
❖ SOFTWARE DESIGN
Modularity and partitioning: Software is designed such that, each system should
consists of hierarchy of modules and serve to partition into separate function.
Shared use: Avoid duplication by allowing a single module be called by other that
need the function it provides.
❖ MODULE DESIGN
Home Module
Home Module:
36
Handles the OAuth flow for obtaining user authorization.
Retrieves user profile information and access tokens for Spotify API interaction.
Displays information about the currently playing song, including the title, artist,
album cover, playback progress, and voting details.
Users can interact with the music player through buttons such as play, pause, and
skip. These buttons trigger actions to control the playback accordingly.
It also displays the number of votes each song has received for skipping
37
❖ DATABASE DESIGN
38
❖ INPUT/OUTPUT DESIGN
Input Design
The input design for the collaborative music playback system involves defining how
users interact with the application to input commands, preferences, and data. Here's an
overview of the input design:
The UI includes various input elements such as text fields, buttons, dropdowns,
and sliders.
Users interact with these elements to perform actions like logging in, creating
rooms, joining rooms, controlling playback, and voting on tracks.
o Authentication Inputs:
Input fields for users to enter their login credentials (username/email and
password) during the authentication process.
Text fields for specifying room preferences such as room name, playback
control permissions, and voting rules.
Text field for entering the room code when joining an existing room.
39
o Playback Control Inputs:
o Voting Inputs:
Output Design
The output design of the project involves presenting information and feedback to
users based on their interactions with the system. Here's an overview of the output
design elements in our collaborative music playback system:
User Interface: The system provides a user-friendly interface using React and
Material-UI components. It includes screens for different functionalities like
home, room creation, room joining, music playback, and settings.
Room Information: Upon joining a room or creating a new one, users see
relevant information such as the room code, current song details, playback
controls, and voting status.
Music Playback: The output design includes a music player interface with
controls for play, pause, and skip. It also displays the current song's title, artist,
album cover, playback progress, and voting details.
40
5.1 DATA MODEL(LIKE DFD)
A Data Flow Diagram (DFD) is a traditional visual representation of the information flows
within a system. A neat and clear DFD can depict the right amount of the system requirement
graphically. It can be manual, automated, or a combination of both.
It shows how data enters and leaves the system, what changes the information, and where
data is stored.
The objective of a DFD is to show the scope and boundaries of a system as a whole. It may
be used as a communication tool between a system analyst and any person who plays a part
in the order that acts as a starting point for redesigning a system. The DFD is also called as a
data flow graph or bubble chart.
41
➢ Source or Destination of Data: External sources or destinations of data, which
may be people or organizations or other entities.
It is also known as a context diagram. It’s designed to be an abstraction view, showing the
system as a single process with its relationship to external entities. It represents the entire
system as a single bubble with input and output data indicated by incoming/outgoing
arrows.
42
5.1.2 Level 1 DFD
This level provides a more detailed view of the system by breaking down the major
processes identified in the level 0 DFD into sub-processes. Each sub-process is depicted as
a separate process on the level 1 DFD. The data flows and data stores associated with each
sub-process are also shown.
In 1-level DFD, the context diagram is decomposed into multiple bubbles/processes. In this
level, we highlight the main functions of the system and breakdown the high-level process
of 0-level DFD into subprocesses.
43
5.2 ENTITY RELATIONSHIP MODEL
ER model stands for an Entity-Relationship model. It is a high-level data model. This model
is used to define the data elements and relationship for a specified system.
It develops a conceptual design for the database. It also develops a very simple and easy to
design view of data.
44
5.4 CLASS DIAGRAM
Class diagrams are a type of UML (Unified Modeling Language) diagram used in software
engineering to visually represent the structure and relationships of classes within a system
i.e. used to construct and visualize object-oriented systems.
45
Class diagrams provide a high-level overview of a system’s design, helping to
communicate and document the structure of the software. They are a fundamental tool in
object-oriented design and play a crucial role in the software development lifecycle.
46
5.5 STATE DIAGRAM/SEQUENCE DIAGRAM
A sequence diagram shows process interactions arranged in time sequence. This diagram
depicts the processes and objects involved and the sequence of messages exchanged as
needed to carry out the functionality.
47
5. SOURCE CODE
6.1 HTML template that provides structure to the application
<!DOCTYPE html>
<html>
<head>
<title>Tune Troop</title>
{% load static %}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<link
rel="stylesheet"
href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700&display=swap"
/>
/>
</head>
<body>
<div id="gradient">
<div id="main">
<div id="app"></div>
</div>
</div>
</body>
</html>
48
6.2 CSS for styling
html,
body {
height: 100%;
margin: 0;
padding: 0;
#main {
position: fixed;
width: 100%;
height: 100%;
left: 0;
top: 0;
#app {
width: 100%;
height: 100%;
.center {
position: absolute;
top: 50%;
left: 50%;
#gradient {
49
width: 100%;
height: 800px;
padding: 0px;
margin: 0px;
[62,35,255],
[60,255,60],
[255,35,98],
[45,175,230],
[255,0,255],
[255,128,0]);
var step = 0;
//transition speed
function updateGradient()
50
{
if ( $===undefined ) return;
$('#gradient').css({
step += gradientSpeed;
if ( step >= 1 )
step %= 1;
51
colorIndices[0] = colorIndices[1];
colorIndices[2] = colorIndices[3];
setInterval(updateGradient,10);
import string
import random
def generate_unique_code():
length = 6
while True:
if Room.objects.filter(code=code).count() == 0:
break
return code
52
class Room(models.Model):
code = models.CharField(
created_at = models.DateTimeField(auto_now_add=True)
6.5 Creation of serializers for the ‘Room’ model in the Django REST
Framework
from rest_framework import serializers
class RoomSerializer(serializers.ModelSerializer):
class Meta:
model = Room
'votes_to_skip', 'created_at')
class CreateRoomSerializer(serializers.ModelSerializer):
class Meta:
model = Room
class UpdateRoomSerializer(serializers.ModelSerializer):
code = serializers.CharField(validators=[])
53
class Meta:
model = Room
fields = ('guest_can_pause', 'votes_to_skip', 'code')
class RoomView(generics.ListAPIView):
queryset = Room.objects.all()
serializer_class = RoomSerializer
class GetRoom(APIView):
serializer_class = RoomSerializer
lookup_url_kwarg = 'code'
code = request.GET.get(self.lookup_url_kwarg)
if code != None:
room = Room.objects.filter(code=code)
if len(room) > 0:
data = RoomSerializer(room[0]).data
54
return Response(data, status=status.HTTP_200_OK)
class JoinRoom(APIView):
lookup_url_kwarg = 'code'
if not self.request.session.exists(self.request.session.session_key):
self.request.session.create()
code = request.data.get(self.lookup_url_kwarg)
if code != None:
room_result = Room.objects.filter(code=code)
if len(room_result) > 0:
room = room_result[0]
self.request.session['room_code'] = code
return Response({'Bad Request': 'Invalid post data, did not find a code key'},
status=status.HTTP_400_BAD_REQUEST)
class CreateRoomView(APIView):
serializer_class = CreateRoomSerializer
55
def post(self, request, format=None):
if not self.request.session.exists(self.request.session.session_key):
self.request.session.create()
serializer = self.serializer_class(data=request.data)
if serializer.is_valid():
guest_can_pause = serializer.data.get('guest_can_pause')
votes_to_skip = serializer.data.get('votes_to_skip')
host = self.request.session.session_key
queryset = Room.objects.filter(host=host)
if queryset.exists():
room = queryset[0]
room.guest_can_pause = guest_can_pause
room.votes_to_skip = votes_to_skip
room.save(update_fields=['guest_can_pause', 'votes_to_skip'])
self.request.session['room_code'] = room.code
else:
votes_to_skip=votes_to_skip)
room.save()
self.request.session['room_code'] = room.code
class UserInRoom(APIView):
56
def get(self, request, format=None):
if not self.request.session.exists(self.request.session.session_key):
self.request.session.create()
data = {
'code': self.request.session.get('room_code')
class LeaveRoom(APIView):
if 'room_code' in self.request.session:
self.request.session.pop('room_code')
host_id = self.request.session.session_key
room_results = Room.objects.filter(host=host_id)
if len(room_results) > 0:
room = room_results[0]
room.delete()
class UpdateRoom(APIView):
serializer_class = UpdateRoomSerializer
if not self.request.session.exists(self.request.session.session_key):
self.request.session.create()
serializer = self.serializer_class(data=request.data)
57
if serializer.is_valid():
guest_can_pause = serializer.data.get('guest_can_pause')
votes_to_skip = serializer.data.get('votes_to_skip')
code = serializer.data.get('code')
queryset = Room.objects.filter(code=code)
if not queryset.exists():
room = queryset[0]
user_id = self.request.session.session_key
if room.host != user_id:
room.guest_can_pause = guest_can_pause
room.votes_to_skip = votes_to_skip
room.save(update_fields=['guest_can_pause', 'votes_to_skip'])
58
urlpatterns = [
path('room', RoomView.as_view()),
path('create-room', CreateRoomView.as_view()),
path('get-room', GetRoom.as_view()),
path('join-room', JoinRoom.as_view()),
path('user-in-room', UserInRoom.as_view()),
path('leave-room', LeaveRoom.as_view()),
path('update-room', UpdateRoom.as_view())
constructor(props) {
super(props);
render() {
return (
<div className="center">
<HomePage />
</div>
);
59
const appDiv = document.getElementById("app");
import { BrowserRouter as Router, Routes, Route, Link, Redirect, Navigate } from 'react-
router-dom';
constructor(props){
super(props);
this.state={
roomCode: null,
};
this.clearRoomCode=this.clearRoomCode.bind(this);
async componentDidMount(){
fetch('/api/user-in-room')
.then((response)=>response.json()).
then((data)=>{
this.setState({
roomCode:data.code,
});
});
60
}
renderHomePage(){
if(this.state.roomCode){
return(
);
}else{
return(
Tune Troop
</Typography>
</Grid>
Create a Room
</Button>
Join a Room
</Button>
</ButtonGroup>
</Grid>
</Grid>
);
61
clearRoomCode(){
this.setState({
roomCode:null,
});
render(){
return (<Router>
<Routes>
/>
</Route>
</Routes>
</Router>);
62
import {FormHelperText} from "@mui/material";
function CreateRoomPage(props){
const navigate=useNavigate();
const[guestCanPause,setguestCanPause]=useState(props.guestCanPause);
const[votesToSkip,setgvotesToSkip]=useState(props.votesToSkip);
const[errorMsg,setErrorMsg]=useState("");
const[successMsg,setSuccessMsg]=useState("");
const handleVotesChange=()=>{
setgvotesToSkip(event.target.value);
};
const handleGuestCanPauseChange=()=>{
setguestCanPause(event.target.value==="true"?true:false);
};
const handleRoomButtonPressed=()=>{
const requestOptions = {
method: 'POST',
63
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({
votes_to_skip:votesToSkip,
guest_can_pause:guestCanPause,
}),
};
fetch('/api/create-room', requestOptions)
.then((response)=>response.json())
};
const handleUpdateButtonPressed=()=>{
const requestOptions = {
method: 'PATCH',
body: JSON.stringify({
votes_to_skip:votesToSkip,
guest_can_pause:guestCanPause,
code:props.roomCode,
}),
};
fetch('/api/update-room', requestOptions)
.then((response)=>{
if(response.ok){
}else{
props.updateCallback();
64
});
};
const renderCreateButtons=()=>{
return(
</Grid>
</Grid>
</Grid>
);
};
const renderUpdateButtons=()=>{
return(
</Grid>
</Grid>
);
};
65
const title=props.update? "Update Room" : "Create a Room";
return (
{successMsg!=""?(
<Alert
severity="success"
onClose={()=>{
setSuccessMsg("");
}}>
{successMsg}
</Alert>
):(
<Alert
severity="error"
onClose={()=>{
setErrorMsg("");
}}>
{errorMsg}
</Alert>
)}
</Collapse>
</Grid>
{title}
</Typography>
66
</Grid>
<FormControl component="fieldset">
<FormHelperText component="div">
</FormHelperText>
labelPlacement="bottom"></FormControlLabel>
</RadioGroup>
</FormControl>
</Grid>
<FormControl>
inputProps={{min:1, style:{textAlign:"center"},}}></TextField>
<FormHelperText component="div">
<div align="center">
</div>
</FormHelperText>
</FormControl>
67
</Grid>
{props.update?renderUpdateButtons(): renderCreateButtons()}
</Grid>
);
CreateRoomPage.defaultProps={
votesToSkip:2,
guestCanPause:true,
update: false,
roomCode:null,
updateCallback:()=>{},
};
const navigate=useNavigate();
const[roomCode, setroomCode]=useState('');
const[errorMsg,seterrorMsg]=useState('');
const[error,seterror]=useState(false);
const handleTextFieldChange=()=>{
68
setroomCode(event.target.value);
};
const roomButtonPressed=()=>{
const requestOptions={
method: "POST",
headers:{"Content-Type": "application/json"},
body:JSON.stringify({
code:roomCode,
}),
};
fetch("/api/join-room",requestOptions).
then((response)=>{
if(response.ok){
navigate("/room/"+ roomCode)
}else{
seterror(true);
})
.catch((error)=>{
console.log(error);
});
};
return(
Join a Room
69
</Typography>
</Grid>
<TextField
error={error}
label="Code"
value={roomCode}
helperText={errorMsg}
variant='outlined'
onChange={handleTextFieldChange}>
</TextField>
</Grid>
<Button
variant='contained'
color='primary'
onClick={roomButtonPressed}>
Enter Room
</Button>
</Grid>
<Button variant='contained'
Back
</Button>
</Grid>
</Grid>
70
);
function Room(props){
const navigate=useNavigate();
const{roomCode}=useParams()
const initialState={
votesToSkip:2,
guestCanPause:false,
isHost:false,
showSettings: false,
spotifyAuthenticated: false,
song:{},
}
const[roomData, setRoomData]=useState(initialState)
useEffect(() => {
getRoomDetails();
return ()=>clearInterval(interval);
},[roomCode]);
71
const getRoomDetails = () => {
.then((response) => {
if (!response.ok) {
props.clearRoomCodeCallback();
navigate("/");
return response.json();
})
.then((data) => {
setRoomData(prevState=>({
...prevState,
votesToSkip: data.votes_to_skip,
guestCanPause: data.guest_can_pause,
isHost: data.is_host
}));
if(data.is_host){
authenticateSpotify();
});
};
const authenticateSpotify=()=>{
fetch("/spotify/is-authenticated")
.then((data) => {
console.log(data.status);
if (!data.status) {
72
fetch("/spotify/get-auth-url")
.then((data) => {
window.location.replace(data.url);
});
});
};
fetch('/spotify/current-song')
.then((response) => {
if (!response.ok) {
return {};
} else {
return response.json();
})
.then((data) => {
console.log(data);
});
};
const leaveButtonPressed=()=>{
const requestOptions={
method: "POST",
headers:{"Content-Type": "application/json"},
};
73
fetch('/api/leave-room',requestOptions).
then((response)=>{
props.clearRoomCodeCallback();
navigate('/');
});
};
const updateShowSettings=(value)=>{
setRoomData({
...roomData,
showSettings:value,
});
};
const renderSettings=()=>{
return(
<Grid container spacing={1}>
<CreateRoomPage
update={true}
votesToSkip={roomData.votesToSkip}
guestCanPause={roomData.guestCanPause}
roomCode={roomCode}
updateCallback={getRoomDetails}
getRoomDetails={getRoomDetails}
/>
</Grid>
<Button
74
variant='contained'
color='secondary'
onClick={()=>updateShowSettings(false)}
>
Close
</Button>
</Grid>
</Grid>
);
};
const renderSettingsButton=()=>{
return(
Settings
</Button>
</Grid>
);
};
return roomData.showSettings?(
renderSettings()
):(
75
Code:{roomCode}
</Typography>
</Grid>
<MusicPlayer {...roomData.song}/>
{roomData.isHost?renderSettingsButton():null}
Leave Room
</Button>
</Grid>
</Grid>
Grid,
Typography,
Card,
IconButton,
LinearProgress,
} from '@mui/material';
76
const requestOptions = {
method: "POST",
headers: { "Content-Type": "application/json" },
};
fetch("/spotify/skip", requestOptions);
};
const requestOptions = {
method: "PUT",
headers: { "Content-Type": "application/json" },
};
fetch("/spotify/pause", requestOptions);
};
const requestOptions = {
method: "PUT",
headers: { "Content-Type": "application/json" },
};
fetch("/spotify/play", requestOptions);
};
return (
<Card>
</Grid>
77
<Grid item align="center" xs={8}>
{props.title}
</Typography>
{props.artist}
</Typography>
<div>
{props.is_playing ? <Pause></Pause> :
<PlayArrowRounded></PlayArrowRounded>}
</IconButton>
<IconButton onClick={()=>skipSong()}>
{props.votes}/{" "}{props.votes_required}
<SkipNext></SkipNext>
</IconButton>
</div>
</Grid>
</Grid>
</Card>
);
};
78
6.14 Django model for storing Spotify authentication tokens and user votes
from django.db import models
class SpotifyToken(models.Model):
created_at = models.DateTimeField(auto_now_add=True)
refresh_token = models.CharField(max_length=150)
access_token = models.CharField(max_length=150)
expires_in = models.DateTimeField()
token_type = models.CharField(max_length=50)
class Vote(models.Model):
created_at = models.DateTimeField(auto_now_add=True)
song_id = models.CharField(max_length=50)
REDIRECT_URI = "http://127.0.0.1:8000/spotify/redirect"
79
from rest_framework.response import Response
class AuthURL(APIView):
'scope': scopes,
'response_type': 'code',
'redirect_uri': REDIRECT_URI,
'client_id': CLIENT_ID
}).prepare().url
code = request.GET.get('code')
error = request.GET.get('error')
'grant_type': 'authorization_code',
'code': code,
'redirect_uri': REDIRECT_URI,
'client_id': CLIENT_ID,
'client_secret': CLIENT_SECRET
80
}).json()
access_token = response.get('access_token')
token_type = response.get('token_type')
refresh_token = response.get('refresh_token')
expires_in = response.get('expires_in')
error = response.get('error')
if not request.session.exists(request.session.session_key):
request.session.create()
update_or_create_user_tokens(
return redirect('frontend:')
class IsAuthenticated(APIView):
is_authenticated = is_spotify_authenticated(
self.request.session.session_key)
class CurrentSong(APIView):
room_code = self.request.session.get('room_code')
room = Room.objects.filter(code=room_code)
if room.exists():
room = room[0]
else:
81
return Response({}, status=status.HTTP_404_NOT_FOUND)
host = room.host
endpoint = "player/currently-playing"
item = response.get('item')
duration = item.get('duration_ms')
progress = response.get('progress_ms')
album_cover = item.get('album').get('images')[0].get('url')
is_playing = response.get('is_playing')
song_id = item.get('id')
artist_string = ""
if i > 0:
name = artist.get('name')
artist_string += name
song = {
'title': item.get('name'),
'artist': artist_string,
'duration': duration,
'time': progress,
82
'image_url': album_cover,
'is_playing': is_playing,
'votes': votes,
'votes_required': room.votes_to_skip,
'id': song_id
self.update_room_song(room, song_id)
current_song = room.current_song
if current_song != song_id:
room.current_song = song_id
room.save(update_fields=['current_song'])
votes = Vote.objects.filter(room=room).delete()
class PauseSong(APIView):
room_code = self.request.session.get('room_code')
room = Room.objects.filter(code=room_code)[0]
pause_song(room.host)
83
class PlaySong(APIView):
room_code = self.request.session.get('room_code')
room = Room.objects.filter(code=room_code)[0]
play_song(room.host)
return Response({}, status=status.HTTP_204_NO_CONTENT)
class SkipSong(APIView):
room_code = self.request.session.get('room_code')
room = Room.objects.filter(code=room_code)[0]
votes_needed = room.votes_to_skip
votes.delete()
skip_song(room.host)
else:
vote = Vote(user=self.request.session.session_key,
room=room, song_id=room.current_song)
vote.save()
84
6.17 To handle Spotify authentication and integration using Spotify API
from .models import SpotifyToken
BASE_URL = "https://api.spotify.com/v1/me/"
def get_user_tokens(session_id):
user_tokens = SpotifyToken.objects.filter(user=session_id)
if user_tokens.exists():
return user_tokens[0]
else:
return None
tokens = get_user_tokens(session_id)
if tokens:
tokens.access_token = access_token
tokens.refresh_token = refresh_token
tokens.expires_in = expires_in
tokens.token_type = token_type
tokens.save(update_fields=['access_token',
'refresh_token', 'expires_in', 'token_type'])
85
else:
refresh_token=refresh_token, token_type=token_type,
expires_in=expires_in)
tokens.save()
def is_spotify_authenticated(session_id):
tokens = get_user_tokens(session_id)
if tokens:
expiry = tokens.expires_in
refresh_spotify_token(session_id)
return True
return False
def refresh_spotify_token(session_id):
refresh_token = get_user_tokens(session_id).refresh_token
'grant_type': 'refresh_token',
'refresh_token': refresh_token,
'client_id': CLIENT_ID,
'client_secret': CLIENT_SECRET
}).json()
access_token = response.get('access_token')
token_type = response.get('token_type')
86
expires_in = response.get('expires_in')
update_or_create_user_tokens(
tokens = get_user_tokens(session_id)
if post_:
if put_:
try:
return response.json()
except:
return {'Error': 'Issue with request'}
def play_song(session_id):
def pause_song(session_id):
def skip_song(session_id):
87
6.18 URL patterns for the API views
from django.urls import path
urlpatterns = [
path('get-auth-url', AuthURL.as_view()),
path('redirect', spotify_callback),
path('is-authenticated', IsAuthenticated.as_view()),
path('current-song', CurrentSong.as_view()),
path('pause', PauseSong.as_view()),
path('play', PlaySong.as_view()),
path('skip', SkipSong.as_view())
6.19 URL pattern to include URLS from different parts of the application
from django.contrib import admin
urlpatterns = [
path('admin/', admin.site.urls),
path('api/', include('api.urls')),
path('', include('frontend.urls')),
path('spotify/', include('spotify.urls'))
88
6. SCREENSHOT
89
7.3 SPOTIFY ACCOUNT LOGIN PAGE
90
7.5 UPDATE ROOM PAGE
91
E-COMMERECE WEB APPLICATION
A Project submitted
in partial fulfilment of the requirements
for the Degree of
By
BIKASH PRADHAN
REGISTRATION NO
22PG030331
22PG0303332
22PG030
2023-2024
GIET UNIVERSITY,GUNUPUR
Department of Computer Science & Applications
Dist. - Rayagada, Odisha-765022
CERTIFICATE
We express our sincere gratitude to Prof. Satya Narayan Das, Head of The Department of
Computer Science and Applications for allowing me to accomplish the project. With his
active support and guidance, this project report has been completed.
We also thank Mr. Ashutosh Mallik our Project Coordinator for guidance and help.
We also thank Mrs. Sucheta Krupalini Moharana our Project Supervisor for guidance and help.
Page Number
Abstract 1
1. Introduction 2-4
1.1 Purpose 2
1.2 Project Scope 2
1.3 Project Features 3-4
2. Literature Review 5-7
3. Problem Statement 8-10
4. System Analysis 11-33
4.1 Identification of Need 11
4.2 Preliminary Investigation 12-13
4.3 Feasibility Study 13 -14
4.4 Project Planning 15-17
4.5 Software Requirement Specifications (SRS) 17-31
4.6 Software Engineering Paradigm Applied 31-33
5. System Design &Specifications 34-47
5.1 Data models (like DFD) 41-43
5.2 Entity Relationship Model 44
5.3 Use-case Diagrams 44-45
5.4 Class Diagrams 45-46
5.5 State Diagrams/Sequence Diagrams 47
6. Source Code 48-88
7. Screenshots 89-92
8. Testing 93-100
8.1 Testing Techniques and Testing Strategies Used Testing Plan used 94-96
8.2 Test Reports for Unit Test Cases and System Test Cases 96-100
9. Conclusion 101-102
10. Future Enhancement 103-105
11. References / Bibliography 106
ABSTRACT
Title: Development of an E-STORE Using Python, D jango, HTML, CSS, and Bootstrap
Abstract:
In today's digital age, online shopping has become increasingly popular, especially for
essential items like groceries. This project aims to develop a comprehensive online
grocery shop using Python, Django, HTML, CSS, and Bootstrap.
The system will provide users with a convenient platform to browse through a wide
range of grocery products, add them to their cart, and securely complete their purchases.
The backend will be powered by Django, a high-level Python web framework, which
will handle user authentication, product management, order processing, and database
interactions.
The frontend will be developed using HTML, CSS, and Bootstrap to create a visually
appealing and responsive user interface. Bootstrap's grid system and components will
ensure that the website is accessible across various devices and screen sizes, providing a
seamless shopping experience for users on desktops, laptops, tablets, and smartphones.
Key features of the online grocery shop will include user registration and login, product
categorization and search functionality, product details and images, shopping cart
management, secure payment processing integration, order tracking, and email
notifications.
Overall, this project aims to leverage modern web development technologies to create
an efficient and user-friendly online grocery shopping platform, catering to the needs of
today's digitally savvy consumers.
1
INTRODUCTION
PURPOSE :
2
PROJECT FEATURES :
Here's a breakdown of the project features for the online grocery shop developed using Python,
Django, HTML, CSS, and Bootstrap:
1. User Registration and Authentication:
- Allow users to register with the platform by providing necessary details.
- Implement authentication mechanisms to ensure secure access to user accounts.
- Enable users to log in and log out of their accounts securely.
2. Product Management:
- Provide functionality for administrators to add, edit, and delete grocery products.
- Include fields such as product name, description, price, quantity, and images.
- Implement product categorization and tagging for easy navigation.
3. Browsing and Searching:
- Enable users to browse through the available grocery products conveniently.
- Implement search functionality to allow users to find specific products quickly.
- Provide filtering options based on categories, prices, and other attributes.
4. Shopping Cart Management:
- Allow users to add products to their shopping carts while browsing.
- Provide options to update the quantity or remove items from the cart.
- Display the total cost and summary of items in the shopping cart.
5. Checkout Process:
- Implement a streamlined checkout process for users to complete their purchases.
- Include forms for users to provide shipping and billing information.
- Integrate secure payment gateways for processing transactions (e.g., PayPal, Stripe).
3
1.1.1 Error Handling and Security: Robust error handling mechanisms and security
measures are implemented to ensure data integrity, user privacy, and protection against
unauthorized access.
4
1. LITERATURE REVIEW
Collaborative music playback systems have emerged as a novel way for users to engage with
music in shared listening experiences. These systems enable multiple users to synchronize
their music playback across devices, allowing for collaborative playlist creation, voting on
tracks, and real-time interaction. This literature review aims to provide a comprehensive
overview of existing research and developments in collaborative music playback systems,
focusing on design principles, technical implementations, user experiences, and the social
impact of these systems.
Looking ahead, future research directions in collaborative music playback systems may
include exploring novel interaction paradigms, integrating emerging technologies like virtual
reality and spatial audio, and investigating the social and cultural implications of shared
6
listening experiences. Moreover, interdisciplinary collaborations between researchers,
designers, musicians, and industry stakeholders can lead to innovative solutions that redefine
how people discover, share, and enjoy music together in the digital age.
7
2. PROBLEM STATEMENT
The problem statement for the project revolves around the need for a collaborative music
playback system that allows multiple users to join a virtual room, synchronize playback, and
control music playback together. Existing music streaming platforms lack real-time
collaboration features, limiting the ability for users to enjoy music together simultaneously.
Therefore, there is a need to develop a platform that enables users to create and join rooms,
interact with other users in real-time, and collectively control music playback. This project
aims to address these limitations by implementing features such as room creation, user
authentication through Spotify, real-time synchronization of playback, and control of
playback features by both hosts and guests.
3.1.2 User Authentication and Integration with Spotify API: Integrating user
authentication via Spotify and leveraging the Spotify API to retrieve and control music
playback requires handling OAuth flows securely and managing access tokens effectively.
3.1.3 Room Management and Data Consistency: Managing rooms dynamically, including
creation, joining, and leaving, while maintaining data consistency and integrity across
connected users presents challenges in database design and synchronization.
3.1.4 Playback Control Permissions: Implementing logic to allow hosts to control playback
permissions for guests, such as play, pause, and skip, requires robust authorization
mechanisms.
3.1.5 Real-Time Updates and Notifications: Enabling real-time updates for playback
control and room settings poses challenges in handling WebSocket communications and
ensuring efficient event propagation.
8
3.1.6 Error Handling and Resilience: Implementing robust error handling mechanisms to
address potential failures in API calls, user authentication, or real-time synchronization is
essential for maintaining a seamless user experience.
• Utilize efficient data structures and algorithms for managing playback state and
ensuring synchronized playback experiences.
• Implement OAuth 2.0 authentication flow securely to authenticate users with their
Spotify accounts.
• Utilize Spotify API endpoints to retrieve user-specific music data, control playback,
and manage user permissions.
• Design a robust database schema to manage rooms, users, and playback state
efficiently.
• Implement role-based access control (RBAC) mechanisms to manage user roles (host
vs. guest) and permissions for controlling playback.
9
3.2.5 Real-Time Updates and Notifications
• Implement robust error handling mechanisms to gracefully handle errors and failures
in API calls, authentication flows, and real-time communication.
• Utilize logging and monitoring tools to track and diagnose errors in real-time,
ensuring quick resolution and minimal disruption to the user experience.
10
3. SYSTEM ANALYSIS
• With the increasing popularity of music streaming services like Spotify, there's a
growing demand for collaborative music playback systems that allow users to listen
to music together in real-time.
• Many users enjoy listening to music with friends or family members, whether they're
in the same location or miles apart. A collaborative music playback system fulfills
the need for shared music listening experiences.
• With the rise of virtual events and gatherings, there's a need for platforms that enable
participants to listen to music together during online parties, virtual hangouts, or
remote celebrations.
• In remote work and learning environments, collaborative music playback systems can
serve as icebreakers, team-building tools, or background entertainment during
virtual meetings and study sessions.
• Users often have diverse musical preferences and tastes. A collaborative music
playback system allows users to share and discover music based on their individual
preferences, creating personalized listening experiences.
11
4.2 PRELIMINARY INVESTIGATION:
The preliminary investigation of this project involves cconducting initial research and
analysis to gather information and assess the feasibility of the project. It includes the
following steps:
• Clarify the project's goals and objectives, such as developing a collaborative music
playback system, integrating with the Spotify API, enabling real-time
synchronization of playback, and providing user-friendly interfaces.
• Assess the technical feasibility of implementing the project, considering factors such
as available resources (e.g., technology stack, development tools), integration with
third-party APIs (e.g., Spotify), and scalability requirements.
• Determine the resources needed for the project, including personnel, time, budget,
hardware, and software. Allocate resources effectively to ensure successful project
execution.
12
4.2.7 Risk Assessment
• Identify potential risks and challenges associated with the project, such as technical
complexities, data security concerns, regulatory compliance, and dependencies on
external factors (e.g., API changes).
• Evaluate the costs and benefits of implementing the project, considering factors such
as development costs, potential revenue streams, market demand, competitive
advantage, and long-term sustainability.
• Assess the technical requirements of integrating with the Spotify API and
implementing real-time synchronization of playback across multiple users.
• Evaluate the compatibility of chosen technologies (Python, Django, React) with the
project requirements.
• Compare the projected costs with the budget allocated for the project to ensure
financial viability.
13
4.3.3 Operational Feasibility
• Evaluate the operational aspects of the project, including how it will be managed,
maintained, and supported post-launch.
• Assess the availability of skilled personnel to develop, deploy, and maintain the
application.
• Consider scalability requirements and whether the project can accommodate growth
in user base and usage over time.
• Identify any legal or regulatory requirements related to music streaming, user data
privacy, copyright, and licensing.
• Ensure compliance with relevant laws and regulations to avoid legal issues and
penalties.
• Analyze the market demand for collaborative music playback systems and the
potential user base for the application.
• Determine if the project fills a gap in the market and offers unique features or
advantages compared to existing solutions.
• Consider any dependencies, constraints, or risks that may impact the project schedule.
• Ensure that the proposed timeline aligns with stakeholders' expectations and business
objectives.
14
4.4 PROJECT PLANNING
Project planning for this collaborative music playback system involves organizing tasks,
allocating resources, and establishing timelines to ensure successful development and
deployment. Here's an outline of the project planning process:
• Clearly articulate the goals and objectives of the project, including the features and
functionality of the collaborative music playback system.
• Break down the project into smaller, manageable tasks and subtasks.
• Estimate the time required to complete each task based on factors such as complexity,
dependencies, and available resources.
• Create a project timeline or Gantt chart that outlines the sequence of tasks, milestones,
and deadlines.
• Identify potential risks and uncertainties that may impact the project schedule, budget,
or quality.
• Develop strategies to mitigate risks and minimize their impact on the project.
15
• Establish contingency plans to address unforeseen challenges that may arise during
development.
• Assign roles and responsibilities to team members based on their skills, expertise, and
availability.
• Regularly monitor project progress against the established schedule and milestones.
• Track resource utilization, budget expenditures, and any deviations from the plan.
• Implement corrective actions as needed to keep the project on track and address any
issues or delays.
• Solicit feedback and address any concerns to ensure stakeholder satisfaction and
alignment with project goals.
• Conduct a post-project review to assess the overall success of the collaborative music
playback system. Evaluate the project against its original objectives, budget, and
schedule.
16
• Prepare a formal project closure report summarizing the project's outcomes,
achievements, and recommendations for future improvements.
4.5.1 Introduction
• User Management
• Music Playback
• Users can play, pause, skip, and control playback of music tracks.
• Real-time Synchronization
• Music playback is synchronized across all connected users in the same room.
• Voting System
• Users can vote to skip tracks, with the option for hosts to set the minimum
number of votes required.
17
• Room Management
• Hosts can close the room, preventing new participants from joining.
• User Interaction
• Users can chat with other participants in the same room, enhancing social
interaction.
• Playback History
• The system maintains a playback history for each room, allowing users to
view previously played tracks and their associated metadata.
• Guest Permissions
• Playlist Management
• Users can create and manage playlists within the application, adding or
removing tracks from their personal collection.
• Hosts can create shared playlists for the entire room to collaborate on.
• Performance
• Security
• Reliability
• Usability
• It should provide feedback and guidance to users as they interact with the
system.
• Accessibility
• Scalability
• The system should adhere to data privacy regulations such as GDPR (General
Data Protection Regulation).
19
• User consent mechanisms should be implemented for data collection and
processing activities.
• Logs should be generated for system events, user actions, and error conditions,
aiding in troubleshooting and auditing.
Spotify API
• Integration with the Spotify API for music playback and user authentication.
Frontend Interface
Database Interface
• Interaction with the database to store user information, room settings, and playback
data.
4.5.5 Constraints
Technology Stack
➢ Front-End Development
HTML, or Hypertext Markup Language, is the standard language used to create and
design web pages. It provides the structure for web content by using various tags and
attributes to define elements on a page. HTML is the backbone of web development,
providing the foundation for creating visually appealing and interactive web pages. It
works hand in hand with CSS (Cascading Style Sheets) for styling and JavaScript for
interactivity, forming the core technologies of the World Wide Web.
20
Overview of HTML
▪ Tags: HTML is built on tags, which are enclosed in angle brackets `< >`. Tags
are used to define different types of content on a webpage, such as headings,
paragraphs, images, links, and more.
▪ Elements: HTML elements are made up of tags and the content they surround.
For example, a paragraph element `<p>` starts with an opening tag and ends with
a closing tag `</p>`, enclosing the paragraph text.
▪ Attributes: Tags can have attributes that provide additional information about an
element. Attributes are placed within the opening tag and typically come inname-
value pairs, such as `href` in an anchor tag `<a href="https://example.com">`.
▪ HTML: The HTML element (`<html>`) is the root element of an HTML page. It
wraps all the content on the page.
▪ Head: The head element (`<head>`) contains metadata and links to external
resources used by the HTML document. It doesn't display any content directly to
the user.
▪ Meta: The meta element (`<meta>`) is used to provide metadata about the HTML
document. Common uses include specifying the character encoding (`charset`
attribute) and setting the viewport for responsive design (`viewport` attribute).
21
▪ Title: The title element (`<title>`) sets the title of the HTML document, which is
displayed in the browser's title bar or tab. It's also used by search engines for page
indexing and in bookmarks.
▪ Div: The div element (`<div>`) is a generic container used to group and style
HTML elements. It's often used to create sections or divisions within a webpage
and is styled using CSS.
▪ Body: The body element (`<body>`) contains the content of the HTML document
that's displayed to the user. It includes text, images, links, forms, and other
elements that make up the visible part of the webpage.
CSS (Cascading Style Sheets) is a language used for describing the presentation
of a document written in HTML (HyperText Markup Language). Here's an overview
of CSS:
▪ Selectors: CSS selectors are patterns used to select the elements you want to
style. They can select elements based on their tag name, class, ID, attributes, and
more. They are a fundamental part of CSS syntax and play a crucial role in
styling web pages.
▪ Properties and Values: CSS properties are the styling attributes you can apply to
selected elements. Each property has a specific value associated with it that
defines how the property should be applied. Examples of properties include
`color`, `font-size`, `background-color`, `margin`, `padding`, and `border`.
▪ Cascading: CSS stands for "Cascading" Style Sheets, which refers to the way
styles are applied to elements. Styles can be inherited from parent elements,
overridden by more specific selectors, or overwritten by inline styles.
▪ Units: CSS supports different units of measurement for specifying sizes and
distances, such as pixels (`px`), percentages (`%`), ems (`em`), rems (`rem`), and
viewport units (`vw`, `vh`, `vmin`, `vmax`).
22
❖ JavaScript
JavaScript (JS) serves as the primary language for adding interactivity and
dynamic behavior to web pages. Here's an overview of JavaScript within the
project context:
23
▪ Animation and Effects: JavaScript can create animations and visual effects on
web pages using techniques like CSS animations, transitions, and
libraries/frameworks such as jQuery or GSAP (GreenSock Animation
Platform).
❖ React
React is a JavaScript library used for building user interfaces, particularly for
single-page applications (SPAs) where content is dynamically updated without
requiring full page reloads. Here's an overview of React within this project:
24
▪ JSX (JavaScript XML): React utilizes JSX, a syntax extension that allows
developers to write HTML-like code within JavaScript. JSX makes it
easier to describe UI components and their structure, combining HTML
markup with JavaScript logic seamlessly.
▪ Props (Properties): React components can receive data via props, which
are essentially read-only inputs passed from parent to child components.
Props allow for communication between components and enable
component customization and reusability.
25
▪ Component Libraries and Ecosystem: React has a rich ecosystem of third-
party libraries and tools that extend its capabilities. This includes state
management libraries like Redux, UI component libraries like Material-UI
or Ant Design, and development tools like React DevTools and Create
React App.
➢ Back-End Development
❖ Python
Python serves as the backend language, responsible for handling server-side logic,
database interactions, and API endpoints. Python serves as the backend language,
responsible for handling server-side logic, database interactions, and API
endpoints.
▪ Django Framework: The project likely uses the Django web framework, which
is a high-level Python web framework that encourages rapid development and
clean, pragmatic design. Django provides a set of built-in tools and
conventions for handling common web development tasks, such as URL
routing, database modeling, and user authentication.
▪ API Endpoints: Python code defines API endpoints using Django's `django-
rest-framework` or similar libraries. These endpoints handle incoming HTTP
requests from the frontend, perform necessary data processing or database
operations, and return appropriate HTTP responses (usually in JSON format)
containing the requested data or indicating the outcome of the request.
❖ Django
Django serves as the web framework for building the backend of the application.
Django provides a comprehensive set of tools and conventions for building web
applications quickly and efficiently. Its batteries-included approach, robust security
features, and thriving ecosystem of third-party packages make it a popular choice
for building scalable and maintainable web applications.
27
views handle the logic to process requests and generate responses, and
templates are used for rendering HTML pages.
▪ URL Routing: Django's URL dispatcher maps URL patterns to view functions
or classes, allowing developers to define how different URLs should be
handled by the application. URL patterns are typically defined in the project's
`urls.py` file and may include regular expressions or path converters to capture
dynamic parts of the URL.
▪ Forms and Validation: Django provides a forms library for handling HTML
forms and form data. Forms can be created using Python classes, and Django
handles tasks such as form rendering, data validation, and error handling
automatically. Forms can be used in views to process user input and interact
with the database.
28
Authorization can be enforced using decorators or middleware to restrict
access to certain views or resources.
▪ Static Files and Media Handling: Django provides utilities for managing static
files (e.g., CSS, JavaScript) and media files (e.g., user-uploaded images,
videos). Static files are typically served directly by the web server in
production, while media files are stored locally or on a cloud storage service
like Amazon S3.
➢ API
❖ Spotify API:
29
access token, which is used to make authenticated requests to the Spotify API
on behalf of the user.
▪ Authorization Code Flow: The application uses the authorization code flow to
authenticate users with Spotify. This flow involves redirecting the user to the
Spotify authorization page with specific parameters, including the client ID,
redirect URI, and requested scopes (permissions). After the user grants
permission, Spotify redirects back to the application with an authorization
code, which is exchanged for an access token and refresh token.
▪ Error Handling and Edge Cases: The application handles potential errors and
edge cases that may arise during interactions with the Spotify API. This
includes scenarios such as invalid access tokens, expired tokens, rate limiting,
and network errors. Error handling mechanisms ensure that the application
provides a smooth and reliable user experience even in the face of API-related
issues.
30
Scalability:
4.5.6 Appendices
Include any additional information relevant to the software requirements, such as use
case diagrams, data flow diagrams, or mockups.
31
4.6.1 Iterative Development: The project can be broken down into smaller increments or
iterations, allowing for continuous improvement and feedback throughout the development
process. Features can be implemented incrementally, with regular demonstrations to
stakeholders for feedback and validation.
4.6.4 Customer-Centric Focus: Agile places a strong emphasis on delivering value to the
customer. In this project, the customer-centric focus means prioritizing features and
functionalities that align with user needs and preferences, ensuring a positive user experience.
4.6.6 Sprint Planning: The project team conducts regular sprint planning meetings to
prioritize tasks and set goals for each iteration. This ensures that development efforts are
focused on delivering the most valuable features incrementally.
4.6.7 Daily Stand-ups: Daily stand-up meetings are held to provide a forum for team
members to discuss progress, identify any impediments, and coordinate their efforts. These
short, focused meetings help maintain alignment and address any issues promptly.
4.6.8 Iterative Feedback: Agile encourages continuous feedback loops, both from
stakeholders and end-users. Regular demos and reviews allow stakeholders to provide
feedback on the product's features and functionality, facilitating early course correction and
improvement.
32
4.6.9 Empowered Teams: Agile principles promote self-organizing, empowered teams that
take ownership of their work. Team members have the autonomy to make decisions and
adapt to changing requirements, fostering a sense of accountability and commitment to
project success.
4.6.11 Adaptive Planning: Agile methodologies recognize that requirements and priorities
may evolve over time. The project plan remains flexible, allowing for adjustments based on
feedback, changes in market conditions, or emerging opportunities.
33
4. SYSTEM DESIGN AND SPECIFICATIONS
The system design and specifications for this project outline the architecture, components,
and functionality of the collaborative music playback system. Here's an overview:
❖ Architecture:
The system follows a client-server architecture, where the server hosts the backend
logic and data storage, while the client interacts with the user through a web-based
interface.
Backend components include Django framework for server-side logic, Spotify API
integration for music playback functionality, and a PostgreSQL database for storing
user data and room information.
Frontend components utilize React.js for building interactive user interfaces and
managing state.
❖ Components:
Backend Components:
• PostgreSQL database for storing user profiles, room details, playback history, and
voting data.
Frontend Components:
• React.js for building modular UI components, managing state, and handling user
interactions.
• Material-UI library for designing responsive and visually appealing user interfaces.
• React Router for client-side routing to navigate between different views within the
application.
34
❖ Functionality:
User Authentication: Users can log in to the system using their Spotify accounts to
access the collaborative music playback features.
Room Management: Hosts can create a room and generate a unique code that other
users can use to join the room. Hosts can also set room preferences such as playback
control permissions and voting requirements.
Music Playback: Users can play, pause, skip tracks, and adjust playback volume
within the room. Playback control permissions are determined by the host's settings.
Voting System: Users can vote to skip tracks, and tracks are skipped when the
required number of votes is reached.
Real-time Updates: Hosts can update playback control settings and voting
requirements in real-time, reflecting changes immediately for all users in the room.
❖ Specifications:
System supports concurrent user sessions with efficient handling of authentication and
session management.
Integration with Spotify API ensures seamless access to music catalogs, playback
control, and user authentication.
Data storage and retrieval operations are optimized for performance and scalability,
ensuring smooth operation even under high user loads.
35
❖ SOFTWARE DESIGN
Modularity and partitioning: Software is designed such that, each system should
consists of hierarchy of modules and serve to partition into separate function.
Shared use: Avoid duplication by allowing a single module be called by other that
need the function it provides.
❖ MODULE DESIGN
Home Module
Home Module:
36
Handles the OAuth flow for obtaining user authorization.
Retrieves user profile information and access tokens for Spotify API interaction.
Displays information about the currently playing song, including the title, artist,
album cover, playback progress, and voting details.
Users can interact with the music player through buttons such as play, pause, and
skip. These buttons trigger actions to control the playback accordingly.
It also displays the number of votes each song has received for skipping
37
❖ DATABASE DESIGN
38
❖ INPUT/OUTPUT DESIGN
Input Design
The input design for the collaborative music playback system involves defining how
users interact with the application to input commands, preferences, and data. Here's an
overview of the input design:
The UI includes various input elements such as text fields, buttons, dropdowns,
and sliders.
Users interact with these elements to perform actions like logging in, creating
rooms, joining rooms, controlling playback, and voting on tracks.
o Authentication Inputs:
Input fields for users to enter their login credentials (username/email and
password) during the authentication process.
Text fields for specifying room preferences such as room name, playback
control permissions, and voting rules.
Text field for entering the room code when joining an existing room.
39
o Playback Control Inputs:
o Voting Inputs:
Output Design
The output design of the project involves presenting information and feedback to
users based on their interactions with the system. Here's an overview of the output
design elements in our collaborative music playback system:
User Interface: The system provides a user-friendly interface using React and
Material-UI components. It includes screens for different functionalities like
home, room creation, room joining, music playback, and settings.
Room Information: Upon joining a room or creating a new one, users see
relevant information such as the room code, current song details, playback
controls, and voting status.
Music Playback: The output design includes a music player interface with
controls for play, pause, and skip. It also displays the current song's title, artist,
album cover, playback progress, and voting details.
40
5.1 DATA MODEL(LIKE DFD)
A Data Flow Diagram (DFD) is a traditional visual representation of the information flows
within a system. A neat and clear DFD can depict the right amount of the system requirement
graphically. It can be manual, automated, or a combination of both.
It shows how data enters and leaves the system, what changes the information, and where
data is stored.
The objective of a DFD is to show the scope and boundaries of a system as a whole. It may
be used as a communication tool between a system analyst and any person who plays a part
in the order that acts as a starting point for redesigning a system. The DFD is also called as a
data flow graph or bubble chart.
41
➢ Source or Destination of Data: External sources or destinations of data, which
may be people or organizations or other entities.
It is also known as a context diagram. It’s designed to be an abstraction view, showing the
system as a single process with its relationship to external entities. It represents the entire
system as a single bubble with input and output data indicated by incoming/outgoing
arrows.
42
5.1.2 Level 1 DFD
This level provides a more detailed view of the system by breaking down the major
processes identified in the level 0 DFD into sub-processes. Each sub-process is depicted as
a separate process on the level 1 DFD. The data flows and data stores associated with each
sub-process are also shown.
In 1-level DFD, the context diagram is decomposed into multiple bubbles/processes. In this
level, we highlight the main functions of the system and breakdown the high-level process
of 0-level DFD into subprocesses.
43
5.2 ENTITY RELATIONSHIP MODEL
ER model stands for an Entity-Relationship model. It is a high-level data model. This model
is used to define the data elements and relationship for a specified system.
It develops a conceptual design for the database. It also develops a very simple and easy to
design view of data.
44
5.4 CLASS DIAGRAM
Class diagrams are a type of UML (Unified Modeling Language) diagram used in software
engineering to visually represent the structure and relationships of classes within a system
i.e. used to construct and visualize object-oriented systems.
45
Class diagrams provide a high-level overview of a system’s design, helping to
communicate and document the structure of the software. They are a fundamental tool in
object-oriented design and play a crucial role in the software development lifecycle.
46
5.5 STATE DIAGRAM/SEQUENCE DIAGRAM
A sequence diagram shows process interactions arranged in time sequence. This diagram
depicts the processes and objects involved and the sequence of messages exchanged as
needed to carry out the functionality.
47
5. SOURCE CODE
6.1 HTML template that provides structure to the application
<!DOCTYPE html>
<html>
<head>
<title>Tune Troop</title>
{% load static %}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<link
rel="stylesheet"
href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700&display=swap"
/>
/>
</head>
<body>
<div id="gradient">
<div id="main">
<div id="app"></div>
</div>
</div>
</body>
</html>
48
6.2 CSS for styling
html,
body {
height: 100%;
margin: 0;
padding: 0;
#main {
position: fixed;
width: 100%;
height: 100%;
left: 0;
top: 0;
#app {
width: 100%;
height: 100%;
.center {
position: absolute;
top: 50%;
left: 50%;
#gradient {
49
width: 100%;
height: 800px;
padding: 0px;
margin: 0px;
[62,35,255],
[60,255,60],
[255,35,98],
[45,175,230],
[255,0,255],
[255,128,0]);
var step = 0;
//transition speed
function updateGradient()
50
{
if ( $===undefined ) return;
$('#gradient').css({
step += gradientSpeed;
if ( step >= 1 )
step %= 1;
51
colorIndices[0] = colorIndices[1];
colorIndices[2] = colorIndices[3];
setInterval(updateGradient,10);
import string
import random
def generate_unique_code():
length = 6
while True:
if Room.objects.filter(code=code).count() == 0:
break
return code
52
class Room(models.Model):
code = models.CharField(
created_at = models.DateTimeField(auto_now_add=True)
6.5 Creation of serializers for the ‘Room’ model in the Django REST
Framework
from rest_framework import serializers
class RoomSerializer(serializers.ModelSerializer):
class Meta:
model = Room
'votes_to_skip', 'created_at')
class CreateRoomSerializer(serializers.ModelSerializer):
class Meta:
model = Room
class UpdateRoomSerializer(serializers.ModelSerializer):
code = serializers.CharField(validators=[])
53
class Meta:
model = Room
fields = ('guest_can_pause', 'votes_to_skip', 'code')
class RoomView(generics.ListAPIView):
queryset = Room.objects.all()
serializer_class = RoomSerializer
class GetRoom(APIView):
serializer_class = RoomSerializer
lookup_url_kwarg = 'code'
code = request.GET.get(self.lookup_url_kwarg)
if code != None:
room = Room.objects.filter(code=code)
if len(room) > 0:
data = RoomSerializer(room[0]).data
54
return Response(data, status=status.HTTP_200_OK)
class JoinRoom(APIView):
lookup_url_kwarg = 'code'
if not self.request.session.exists(self.request.session.session_key):
self.request.session.create()
code = request.data.get(self.lookup_url_kwarg)
if code != None:
room_result = Room.objects.filter(code=code)
if len(room_result) > 0:
room = room_result[0]
self.request.session['room_code'] = code
return Response({'Bad Request': 'Invalid post data, did not find a code key'},
status=status.HTTP_400_BAD_REQUEST)
class CreateRoomView(APIView):
serializer_class = CreateRoomSerializer
55
def post(self, request, format=None):
if not self.request.session.exists(self.request.session.session_key):
self.request.session.create()
serializer = self.serializer_class(data=request.data)
if serializer.is_valid():
guest_can_pause = serializer.data.get('guest_can_pause')
votes_to_skip = serializer.data.get('votes_to_skip')
host = self.request.session.session_key
queryset = Room.objects.filter(host=host)
if queryset.exists():
room = queryset[0]
room.guest_can_pause = guest_can_pause
room.votes_to_skip = votes_to_skip
room.save(update_fields=['guest_can_pause', 'votes_to_skip'])
self.request.session['room_code'] = room.code
else:
votes_to_skip=votes_to_skip)
room.save()
self.request.session['room_code'] = room.code
class UserInRoom(APIView):
56
def get(self, request, format=None):
if not self.request.session.exists(self.request.session.session_key):
self.request.session.create()
data = {
'code': self.request.session.get('room_code')
class LeaveRoom(APIView):
if 'room_code' in self.request.session:
self.request.session.pop('room_code')
host_id = self.request.session.session_key
room_results = Room.objects.filter(host=host_id)
if len(room_results) > 0:
room = room_results[0]
room.delete()
class UpdateRoom(APIView):
serializer_class = UpdateRoomSerializer
if not self.request.session.exists(self.request.session.session_key):
self.request.session.create()
serializer = self.serializer_class(data=request.data)
57
if serializer.is_valid():
guest_can_pause = serializer.data.get('guest_can_pause')
votes_to_skip = serializer.data.get('votes_to_skip')
code = serializer.data.get('code')
queryset = Room.objects.filter(code=code)
if not queryset.exists():
room = queryset[0]
user_id = self.request.session.session_key
if room.host != user_id:
room.guest_can_pause = guest_can_pause
room.votes_to_skip = votes_to_skip
room.save(update_fields=['guest_can_pause', 'votes_to_skip'])
58
urlpatterns = [
path('room', RoomView.as_view()),
path('create-room', CreateRoomView.as_view()),
path('get-room', GetRoom.as_view()),
path('join-room', JoinRoom.as_view()),
path('user-in-room', UserInRoom.as_view()),
path('leave-room', LeaveRoom.as_view()),
path('update-room', UpdateRoom.as_view())
constructor(props) {
super(props);
render() {
return (
<div className="center">
<HomePage />
</div>
);
59
const appDiv = document.getElementById("app");
import { BrowserRouter as Router, Routes, Route, Link, Redirect, Navigate } from 'react-
router-dom';
constructor(props){
super(props);
this.state={
roomCode: null,
};
this.clearRoomCode=this.clearRoomCode.bind(this);
async componentDidMount(){
fetch('/api/user-in-room')
.then((response)=>response.json()).
then((data)=>{
this.setState({
roomCode:data.code,
});
});
60
}
renderHomePage(){
if(this.state.roomCode){
return(
);
}else{
return(
Tune Troop
</Typography>
</Grid>
Create a Room
</Button>
Join a Room
</Button>
</ButtonGroup>
</Grid>
</Grid>
);
61
clearRoomCode(){
this.setState({
roomCode:null,
});
render(){
return (<Router>
<Routes>
/>
</Route>
</Routes>
</Router>);
62
import {FormHelperText} from "@mui/material";
function CreateRoomPage(props){
const navigate=useNavigate();
const[guestCanPause,setguestCanPause]=useState(props.guestCanPause);
const[votesToSkip,setgvotesToSkip]=useState(props.votesToSkip);
const[errorMsg,setErrorMsg]=useState("");
const[successMsg,setSuccessMsg]=useState("");
const handleVotesChange=()=>{
setgvotesToSkip(event.target.value);
};
const handleGuestCanPauseChange=()=>{
setguestCanPause(event.target.value==="true"?true:false);
};
const handleRoomButtonPressed=()=>{
const requestOptions = {
method: 'POST',
63
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({
votes_to_skip:votesToSkip,
guest_can_pause:guestCanPause,
}),
};
fetch('/api/create-room', requestOptions)
.then((response)=>response.json())
};
const handleUpdateButtonPressed=()=>{
const requestOptions = {
method: 'PATCH',
body: JSON.stringify({
votes_to_skip:votesToSkip,
guest_can_pause:guestCanPause,
code:props.roomCode,
}),
};
fetch('/api/update-room', requestOptions)
.then((response)=>{
if(response.ok){
}else{
props.updateCallback();
64
});
};
const renderCreateButtons=()=>{
return(
</Grid>
</Grid>
</Grid>
);
};
const renderUpdateButtons=()=>{
return(
</Grid>
</Grid>
);
};
65
const title=props.update? "Update Room" : "Create a Room";
return (
{successMsg!=""?(
<Alert
severity="success"
onClose={()=>{
setSuccessMsg("");
}}>
{successMsg}
</Alert>
):(
<Alert
severity="error"
onClose={()=>{
setErrorMsg("");
}}>
{errorMsg}
</Alert>
)}
</Collapse>
</Grid>
{title}
</Typography>
66
</Grid>
<FormControl component="fieldset">
<FormHelperText component="div">
</FormHelperText>
labelPlacement="bottom"></FormControlLabel>
</RadioGroup>
</FormControl>
</Grid>
<FormControl>
inputProps={{min:1, style:{textAlign:"center"},}}></TextField>
<FormHelperText component="div">
<div align="center">
</div>
</FormHelperText>
</FormControl>
67
</Grid>
{props.update?renderUpdateButtons(): renderCreateButtons()}
</Grid>
);
CreateRoomPage.defaultProps={
votesToSkip:2,
guestCanPause:true,
update: false,
roomCode:null,
updateCallback:()=>{},
};
const navigate=useNavigate();
const[roomCode, setroomCode]=useState('');
const[errorMsg,seterrorMsg]=useState('');
const[error,seterror]=useState(false);
const handleTextFieldChange=()=>{
68
setroomCode(event.target.value);
};
const roomButtonPressed=()=>{
const requestOptions={
method: "POST",
headers:{"Content-Type": "application/json"},
body:JSON.stringify({
code:roomCode,
}),
};
fetch("/api/join-room",requestOptions).
then((response)=>{
if(response.ok){
navigate("/room/"+ roomCode)
}else{
seterror(true);
})
.catch((error)=>{
console.log(error);
});
};
return(
Join a Room
69
</Typography>
</Grid>
<TextField
error={error}
label="Code"
value={roomCode}
helperText={errorMsg}
variant='outlined'
onChange={handleTextFieldChange}>
</TextField>
</Grid>
<Button
variant='contained'
color='primary'
onClick={roomButtonPressed}>
Enter Room
</Button>
</Grid>
<Button variant='contained'
Back
</Button>
</Grid>
</Grid>
70
);
function Room(props){
const navigate=useNavigate();
const{roomCode}=useParams()
const initialState={
votesToSkip:2,
guestCanPause:false,
isHost:false,
showSettings: false,
spotifyAuthenticated: false,
song:{},
}
const[roomData, setRoomData]=useState(initialState)
useEffect(() => {
getRoomDetails();
return ()=>clearInterval(interval);
},[roomCode]);
71
const getRoomDetails = () => {
.then((response) => {
if (!response.ok) {
props.clearRoomCodeCallback();
navigate("/");
return response.json();
})
.then((data) => {
setRoomData(prevState=>({
...prevState,
votesToSkip: data.votes_to_skip,
guestCanPause: data.guest_can_pause,
isHost: data.is_host
}));
if(data.is_host){
authenticateSpotify();
});
};
const authenticateSpotify=()=>{
fetch("/spotify/is-authenticated")
.then((data) => {
console.log(data.status);
if (!data.status) {
72
fetch("/spotify/get-auth-url")
.then((data) => {
window.location.replace(data.url);
});
});
};
fetch('/spotify/current-song')
.then((response) => {
if (!response.ok) {
return {};
} else {
return response.json();
})
.then((data) => {
console.log(data);
});
};
const leaveButtonPressed=()=>{
const requestOptions={
method: "POST",
headers:{"Content-Type": "application/json"},
};
73
fetch('/api/leave-room',requestOptions).
then((response)=>{
props.clearRoomCodeCallback();
navigate('/');
});
};
const updateShowSettings=(value)=>{
setRoomData({
...roomData,
showSettings:value,
});
};
const renderSettings=()=>{
return(
<Grid container spacing={1}>
<CreateRoomPage
update={true}
votesToSkip={roomData.votesToSkip}
guestCanPause={roomData.guestCanPause}
roomCode={roomCode}
updateCallback={getRoomDetails}
getRoomDetails={getRoomDetails}
/>
</Grid>
<Button
74
variant='contained'
color='secondary'
onClick={()=>updateShowSettings(false)}
>
Close
</Button>
</Grid>
</Grid>
);
};
const renderSettingsButton=()=>{
return(
Settings
</Button>
</Grid>
);
};
return roomData.showSettings?(
renderSettings()
):(
75
Code:{roomCode}
</Typography>
</Grid>
<MusicPlayer {...roomData.song}/>
{roomData.isHost?renderSettingsButton():null}
Leave Room
</Button>
</Grid>
</Grid>
Grid,
Typography,
Card,
IconButton,
LinearProgress,
} from '@mui/material';
76
const requestOptions = {
method: "POST",
headers: { "Content-Type": "application/json" },
};
fetch("/spotify/skip", requestOptions);
};
const requestOptions = {
method: "PUT",
headers: { "Content-Type": "application/json" },
};
fetch("/spotify/pause", requestOptions);
};
const requestOptions = {
method: "PUT",
headers: { "Content-Type": "application/json" },
};
fetch("/spotify/play", requestOptions);
};
return (
<Card>
</Grid>
77
<Grid item align="center" xs={8}>
{props.title}
</Typography>
{props.artist}
</Typography>
<div>
{props.is_playing ? <Pause></Pause> :
<PlayArrowRounded></PlayArrowRounded>}
</IconButton>
<IconButton onClick={()=>skipSong()}>
{props.votes}/{" "}{props.votes_required}
<SkipNext></SkipNext>
</IconButton>
</div>
</Grid>
</Grid>
</Card>
);
};
78
6.14 Django model for storing Spotify authentication tokens and user votes
from django.db import models
class SpotifyToken(models.Model):
created_at = models.DateTimeField(auto_now_add=True)
refresh_token = models.CharField(max_length=150)
access_token = models.CharField(max_length=150)
expires_in = models.DateTimeField()
token_type = models.CharField(max_length=50)
class Vote(models.Model):
created_at = models.DateTimeField(auto_now_add=True)
song_id = models.CharField(max_length=50)
REDIRECT_URI = "http://127.0.0.1:8000/spotify/redirect"
79
from rest_framework.response import Response
class AuthURL(APIView):
'scope': scopes,
'response_type': 'code',
'redirect_uri': REDIRECT_URI,
'client_id': CLIENT_ID
}).prepare().url
code = request.GET.get('code')
error = request.GET.get('error')
'grant_type': 'authorization_code',
'code': code,
'redirect_uri': REDIRECT_URI,
'client_id': CLIENT_ID,
'client_secret': CLIENT_SECRET
80
}).json()
access_token = response.get('access_token')
token_type = response.get('token_type')
refresh_token = response.get('refresh_token')
expires_in = response.get('expires_in')
error = response.get('error')
if not request.session.exists(request.session.session_key):
request.session.create()
update_or_create_user_tokens(
return redirect('frontend:')
class IsAuthenticated(APIView):
is_authenticated = is_spotify_authenticated(
self.request.session.session_key)
class CurrentSong(APIView):
room_code = self.request.session.get('room_code')
room = Room.objects.filter(code=room_code)
if room.exists():
room = room[0]
else:
81
return Response({}, status=status.HTTP_404_NOT_FOUND)
host = room.host
endpoint = "player/currently-playing"
item = response.get('item')
duration = item.get('duration_ms')
progress = response.get('progress_ms')
album_cover = item.get('album').get('images')[0].get('url')
is_playing = response.get('is_playing')
song_id = item.get('id')
artist_string = ""
if i > 0:
name = artist.get('name')
artist_string += name
song = {
'title': item.get('name'),
'artist': artist_string,
'duration': duration,
'time': progress,
82
'image_url': album_cover,
'is_playing': is_playing,
'votes': votes,
'votes_required': room.votes_to_skip,
'id': song_id
self.update_room_song(room, song_id)
current_song = room.current_song
if current_song != song_id:
room.current_song = song_id
room.save(update_fields=['current_song'])
votes = Vote.objects.filter(room=room).delete()
class PauseSong(APIView):
room_code = self.request.session.get('room_code')
room = Room.objects.filter(code=room_code)[0]
pause_song(room.host)
83
class PlaySong(APIView):
room_code = self.request.session.get('room_code')
room = Room.objects.filter(code=room_code)[0]
play_song(room.host)
return Response({}, status=status.HTTP_204_NO_CONTENT)
class SkipSong(APIView):
room_code = self.request.session.get('room_code')
room = Room.objects.filter(code=room_code)[0]
votes_needed = room.votes_to_skip
votes.delete()
skip_song(room.host)
else:
vote = Vote(user=self.request.session.session_key,
room=room, song_id=room.current_song)
vote.save()
84
6.17 To handle Spotify authentication and integration using Spotify API
from .models import SpotifyToken
BASE_URL = "https://api.spotify.com/v1/me/"
def get_user_tokens(session_id):
user_tokens = SpotifyToken.objects.filter(user=session_id)
if user_tokens.exists():
return user_tokens[0]
else:
return None
tokens = get_user_tokens(session_id)
if tokens:
tokens.access_token = access_token
tokens.refresh_token = refresh_token
tokens.expires_in = expires_in
tokens.token_type = token_type
tokens.save(update_fields=['access_token',
'refresh_token', 'expires_in', 'token_type'])
85
else:
refresh_token=refresh_token, token_type=token_type,
expires_in=expires_in)
tokens.save()
def is_spotify_authenticated(session_id):
tokens = get_user_tokens(session_id)
if tokens:
expiry = tokens.expires_in
refresh_spotify_token(session_id)
return True
return False
def refresh_spotify_token(session_id):
refresh_token = get_user_tokens(session_id).refresh_token
'grant_type': 'refresh_token',
'refresh_token': refresh_token,
'client_id': CLIENT_ID,
'client_secret': CLIENT_SECRET
}).json()
access_token = response.get('access_token')
token_type = response.get('token_type')
86
expires_in = response.get('expires_in')
update_or_create_user_tokens(
tokens = get_user_tokens(session_id)
if post_:
if put_:
try:
return response.json()
except:
return {'Error': 'Issue with request'}
def play_song(session_id):
def pause_song(session_id):
def skip_song(session_id):
87
6.18 URL patterns for the API views
from django.urls import path
urlpatterns = [
path('get-auth-url', AuthURL.as_view()),
path('redirect', spotify_callback),
path('is-authenticated', IsAuthenticated.as_view()),
path('current-song', CurrentSong.as_view()),
path('pause', PauseSong.as_view()),
path('play', PlaySong.as_view()),
path('skip', SkipSong.as_view())
6.19 URL pattern to include URLS from different parts of the application
from django.contrib import admin
urlpatterns = [
path('admin/', admin.site.urls),
path('api/', include('api.urls')),
path('', include('frontend.urls')),
path('spotify/', include('spotify.urls'))
88
6. SCREENSHOT
89
7.3 SPOTIFY ACCOUNT LOGIN PAGE
90
7.5 UPDATE ROOM PAGE
91
7.5 MUSIC PLAYER PAGE FOR GUEST
92
GIET UNIVERSITY,GUNUPUR
Department of Computer Science & Applications
Dist. - Rayagada, Odisha-765022
CERTIFICATE
We express our sincere gratitude to Prof. Satya Narayan Das, Head of The Department of
Computer Science and Applications for allowing me to accomplish the project. With his
active support and guidance, this project report has been completed.
We also thank Mr. Ashutosh Mallik our Project Coordinator for guidance and help.
We also thank Mrs. Sucheta Krupalini Moharana our Project Supervisor for guidance and help.
Page Number
Abstract 1
1. Introduction 2-4
1.1 Purpose 2
1.2 Project Scope 2
1.3 Project Features 3-4
2. Literature Review 5-7
3. Problem Statement 8-10
4. System Analysis 11-33
4.1 Identification of Need 11
4.2 Preliminary Investigation 12-13
4.3 Feasibility Study 13 -14
4.4 Project Planning 15-17
4.5 Software Requirement Specifications (SRS) 17-31
4.6 Software Engineering Paradigm Applied 31-33
5. System Design &Specifications 34-47
5.1 Data models (like DFD) 41-43
5.2 Entity Relationship Model 44
5.3 Use-case Diagrams 44-45
5.4 Class Diagrams 45-46
5.5 State Diagrams/Sequence Diagrams 47
6. Source Code 48-88
7. Screenshots 89-92
8. Testing 93-100
8.1 Testing Techniques and Testing Strategies Used Testing Plan used 94-96
8.2 Test Reports for Unit Test Cases and System Test Cases 96-100
9. Conclusion 101-102
10. Future Enhancement 103-105
11. References / Bibliography 106
ABSTRACT
Title: Development of an E-STORE Using Python, D jango, HTML, CSS, and Bootstrap
Abstract:
In today's digital age, online shopping has become increasingly popular, especially for
essential items like groceries. This project aims to develop a comprehensive online
grocery shop using Python, Django, HTML, CSS, and Bootstrap.
The system will provide users with a convenient platform to browse through a wide
range of grocery products, add them to their cart, and securely complete their purchases.
The backend will be powered by Django, a high-level Python web framework, which
will handle user authentication, product management, order processing, and database
interactions.
The frontend will be developed using HTML, CSS, and Bootstrap to create a visually
appealing and responsive user interface. Bootstrap's grid system and components will
ensure that the website is accessible across various devices and screen sizes, providing a
seamless shopping experience for users on desktops, laptops, tablets, and smartphones.
Key features of the online grocery shop will include user registration and login, product
categorization and search functionality, product details and images, shopping cart
management, secure payment processing integration, order tracking, and email
notifications.
Overall, this project aims to leverage modern web development technologies to create
an efficient and user-friendly online grocery shopping platform, catering to the needs of
today's digitally savvy consumers.
1
INTRODUCTION
PURPOSE :
2
PROJECT FEATURES :
Here's a breakdown of the project features for the online grocery shop developed using Python,
Django, HTML, CSS, and Bootstrap:
1. User Registration and Authentication:
- Allow users to register with the platform by providing necessary details.
- Implement authentication mechanisms to ensure secure access to user accounts.
- Enable users to log in and log out of their accounts securely.
2. Product Management:
- Provide functionality for administrators to add, edit, and delete grocery products.
- Include fields such as product name, description, price, quantity, and images.
- Implement product categorization and tagging for easy navigation.
3. Browsing and Searching:
- Enable users to browse through the available grocery products conveniently.
- Implement search functionality to allow users to find specific products quickly.
- Provide filtering options based on categories, prices, and other attributes.
4. Shopping Cart Management:
- Allow users to add products to their shopping carts while browsing.
- Provide options to update the quantity or remove items from the cart.
- Display the total cost and summary of items in the shopping cart.
5. Checkout Process:
- Implement a streamlined checkout process for users to complete their purchases.
- Include forms for users to provide shipping and billing information.
- Integrate secure payment gateways for processing transactions (e.g., PayPal, Stripe).
3
1.1.1 Error Handling and Security: Robust error handling mechanisms and security
measures are implemented to ensure data integrity, user privacy, and protection against
unauthorized access.
4
1. LITERATURE REVIEW
Collaborative music playback systems have emerged as a novel way for users to engage with
music in shared listening experiences. These systems enable multiple users to synchronize
their music playback across devices, allowing for collaborative playlist creation, voting on
tracks, and real-time interaction. This literature review aims to provide a comprehensive
overview of existing research and developments in collaborative music playback systems,
focusing on design principles, technical implementations, user experiences, and the social
impact of these systems.
Looking ahead, future research directions in collaborative music playback systems may
include exploring novel interaction paradigms, integrating emerging technologies like virtual
reality and spatial audio, and investigating the social and cultural implications of shared
6
listening experiences. Moreover, interdisciplinary collaborations between researchers,
designers, musicians, and industry stakeholders can lead to innovative solutions that redefine
how people discover, share, and enjoy music together in the digital age.
7
2. PROBLEM STATEMENT
The problem statement for the project revolves around the need for a collaborative music
playback system that allows multiple users to join a virtual room, synchronize playback, and
control music playback together. Existing music streaming platforms lack real-time
collaboration features, limiting the ability for users to enjoy music together simultaneously.
Therefore, there is a need to develop a platform that enables users to create and join rooms,
interact with other users in real-time, and collectively control music playback. This project
aims to address these limitations by implementing features such as room creation, user
authentication through Spotify, real-time synchronization of playback, and control of
playback features by both hosts and guests.
3.1.2 User Authentication and Integration with Spotify API: Integrating user
authentication via Spotify and leveraging the Spotify API to retrieve and control music
playback requires handling OAuth flows securely and managing access tokens effectively.
3.1.3 Room Management and Data Consistency: Managing rooms dynamically, including
creation, joining, and leaving, while maintaining data consistency and integrity across
connected users presents challenges in database design and synchronization.
3.1.4 Playback Control Permissions: Implementing logic to allow hosts to control playback
permissions for guests, such as play, pause, and skip, requires robust authorization
mechanisms.
3.1.5 Real-Time Updates and Notifications: Enabling real-time updates for playback
control and room settings poses challenges in handling WebSocket communications and
ensuring efficient event propagation.
8
3.1.6 Error Handling and Resilience: Implementing robust error handling mechanisms to
address potential failures in API calls, user authentication, or real-time synchronization is
essential for maintaining a seamless user experience.
• Utilize efficient data structures and algorithms for managing playback state and
ensuring synchronized playback experiences.
• Implement OAuth 2.0 authentication flow securely to authenticate users with their
Spotify accounts.
• Utilize Spotify API endpoints to retrieve user-specific music data, control playback,
and manage user permissions.
• Design a robust database schema to manage rooms, users, and playback state
efficiently.
• Implement role-based access control (RBAC) mechanisms to manage user roles (host
vs. guest) and permissions for controlling playback.
9
3.2.5 Real-Time Updates and Notifications
• Implement robust error handling mechanisms to gracefully handle errors and failures
in API calls, authentication flows, and real-time communication.
• Utilize logging and monitoring tools to track and diagnose errors in real-time,
ensuring quick resolution and minimal disruption to the user experience.
10
3. SYSTEM ANALYSIS
• With the increasing popularity of music streaming services like Spotify, there's a
growing demand for collaborative music playback systems that allow users to listen
to music together in real-time.
• Many users enjoy listening to music with friends or family members, whether they're
in the same location or miles apart. A collaborative music playback system fulfills
the need for shared music listening experiences.
• With the rise of virtual events and gatherings, there's a need for platforms that enable
participants to listen to music together during online parties, virtual hangouts, or
remote celebrations.
• In remote work and learning environments, collaborative music playback systems can
serve as icebreakers, team-building tools, or background entertainment during
virtual meetings and study sessions.
• Users often have diverse musical preferences and tastes. A collaborative music
playback system allows users to share and discover music based on their individual
preferences, creating personalized listening experiences.
11
4.2 PRELIMINARY INVESTIGATION:
The preliminary investigation of this project involves cconducting initial research and
analysis to gather information and assess the feasibility of the project. It includes the
following steps:
• Clarify the project's goals and objectives, such as developing a collaborative music
playback system, integrating with the Spotify API, enabling real-time
synchronization of playback, and providing user-friendly interfaces.
• Assess the technical feasibility of implementing the project, considering factors such
as available resources (e.g., technology stack, development tools), integration with
third-party APIs (e.g., Spotify), and scalability requirements.
• Determine the resources needed for the project, including personnel, time, budget,
hardware, and software. Allocate resources effectively to ensure successful project
execution.
12
4.2.7 Risk Assessment
• Identify potential risks and challenges associated with the project, such as technical
complexities, data security concerns, regulatory compliance, and dependencies on
external factors (e.g., API changes).
• Evaluate the costs and benefits of implementing the project, considering factors such
as development costs, potential revenue streams, market demand, competitive
advantage, and long-term sustainability.
• Assess the technical requirements of integrating with the Spotify API and
implementing real-time synchronization of playback across multiple users.
• Evaluate the compatibility of chosen technologies (Python, Django, React) with the
project requirements.
• Compare the projected costs with the budget allocated for the project to ensure
financial viability.
13
4.3.3 Operational Feasibility
• Evaluate the operational aspects of the project, including how it will be managed,
maintained, and supported post-launch.
• Assess the availability of skilled personnel to develop, deploy, and maintain the
application.
• Consider scalability requirements and whether the project can accommodate growth
in user base and usage over time.
• Identify any legal or regulatory requirements related to music streaming, user data
privacy, copyright, and licensing.
• Ensure compliance with relevant laws and regulations to avoid legal issues and
penalties.
• Analyze the market demand for collaborative music playback systems and the
potential user base for the application.
• Determine if the project fills a gap in the market and offers unique features or
advantages compared to existing solutions.
• Consider any dependencies, constraints, or risks that may impact the project schedule.
• Ensure that the proposed timeline aligns with stakeholders' expectations and business
objectives.
14
4.4 PROJECT PLANNING
Project planning for this collaborative music playback system involves organizing tasks,
allocating resources, and establishing timelines to ensure successful development and
deployment. Here's an outline of the project planning process:
• Clearly articulate the goals and objectives of the project, including the features and
functionality of the collaborative music playback system.
• Break down the project into smaller, manageable tasks and subtasks.
• Estimate the time required to complete each task based on factors such as complexity,
dependencies, and available resources.
• Create a project timeline or Gantt chart that outlines the sequence of tasks, milestones,
and deadlines.
• Identify potential risks and uncertainties that may impact the project schedule, budget,
or quality.
• Develop strategies to mitigate risks and minimize their impact on the project.
15
• Establish contingency plans to address unforeseen challenges that may arise during
development.
• Assign roles and responsibilities to team members based on their skills, expertise, and
availability.
• Regularly monitor project progress against the established schedule and milestones.
• Track resource utilization, budget expenditures, and any deviations from the plan.
• Implement corrective actions as needed to keep the project on track and address any
issues or delays.
• Solicit feedback and address any concerns to ensure stakeholder satisfaction and
alignment with project goals.
• Conduct a post-project review to assess the overall success of the collaborative music
playback system. Evaluate the project against its original objectives, budget, and
schedule.
16
• Prepare a formal project closure report summarizing the project's outcomes,
achievements, and recommendations for future improvements.
4.5.1 Introduction
• User Management
• Music Playback
• Users can play, pause, skip, and control playback of music tracks.
• Real-time Synchronization
• Music playback is synchronized across all connected users in the same room.
• Voting System
• Users can vote to skip tracks, with the option for hosts to set the minimum
number of votes required.
17
• Room Management
• Hosts can close the room, preventing new participants from joining.
• User Interaction
• Users can chat with other participants in the same room, enhancing social
interaction.
• Playback History
• The system maintains a playback history for each room, allowing users to
view previously played tracks and their associated metadata.
• Guest Permissions
• Playlist Management
• Users can create and manage playlists within the application, adding or
removing tracks from their personal collection.
• Hosts can create shared playlists for the entire room to collaborate on.
• Performance
• Security
• Reliability
• Usability
• It should provide feedback and guidance to users as they interact with the
system.
• Accessibility
• Scalability
• The system should adhere to data privacy regulations such as GDPR (General
Data Protection Regulation).
19
• User consent mechanisms should be implemented for data collection and
processing activities.
• Logs should be generated for system events, user actions, and error conditions,
aiding in troubleshooting and auditing.
Spotify API
• Integration with the Spotify API for music playback and user authentication.
Frontend Interface
Database Interface
• Interaction with the database to store user information, room settings, and playback
data.
4.5.5 Constraints
Technology Stack
➢ Front-End Development
HTML, or Hypertext Markup Language, is the standard language used to create and
design web pages. It provides the structure for web content by using various tags and
attributes to define elements on a page. HTML is the backbone of web development,
providing the foundation for creating visually appealing and interactive web pages. It
works hand in hand with CSS (Cascading Style Sheets) for styling and JavaScript for
interactivity, forming the core technologies of the World Wide Web.
20
Overview of HTML
▪ Tags: HTML is built on tags, which are enclosed in angle brackets `< >`. Tags
are used to define different types of content on a webpage, such as headings,
paragraphs, images, links, and more.
▪ Elements: HTML elements are made up of tags and the content they surround.
For example, a paragraph element `<p>` starts with an opening tag and ends with
a closing tag `</p>`, enclosing the paragraph text.
▪ Attributes: Tags can have attributes that provide additional information about an
element. Attributes are placed within the opening tag and typically come inname-
value pairs, such as `href` in an anchor tag `<a href="https://example.com">`.
▪ HTML: The HTML element (`<html>`) is the root element of an HTML page. It
wraps all the content on the page.
▪ Head: The head element (`<head>`) contains metadata and links to external
resources used by the HTML document. It doesn't display any content directly to
the user.
▪ Meta: The meta element (`<meta>`) is used to provide metadata about the HTML
document. Common uses include specifying the character encoding (`charset`
attribute) and setting the viewport for responsive design (`viewport` attribute).
21
▪ Title: The title element (`<title>`) sets the title of the HTML document, which is
displayed in the browser's title bar or tab. It's also used by search engines for page
indexing and in bookmarks.
▪ Div: The div element (`<div>`) is a generic container used to group and style
HTML elements. It's often used to create sections or divisions within a webpage
and is styled using CSS.
▪ Body: The body element (`<body>`) contains the content of the HTML document
that's displayed to the user. It includes text, images, links, forms, and other
elements that make up the visible part of the webpage.
CSS (Cascading Style Sheets) is a language used for describing the presentation
of a document written in HTML (HyperText Markup Language). Here's an overview
of CSS:
▪ Selectors: CSS selectors are patterns used to select the elements you want to
style. They can select elements based on their tag name, class, ID, attributes, and
more. They are a fundamental part of CSS syntax and play a crucial role in
styling web pages.
▪ Properties and Values: CSS properties are the styling attributes you can apply to
selected elements. Each property has a specific value associated with it that
defines how the property should be applied. Examples of properties include
`color`, `font-size`, `background-color`, `margin`, `padding`, and `border`.
▪ Cascading: CSS stands for "Cascading" Style Sheets, which refers to the way
styles are applied to elements. Styles can be inherited from parent elements,
overridden by more specific selectors, or overwritten by inline styles.
▪ Units: CSS supports different units of measurement for specifying sizes and
distances, such as pixels (`px`), percentages (`%`), ems (`em`), rems (`rem`), and
viewport units (`vw`, `vh`, `vmin`, `vmax`).
22
❖ JavaScript
JavaScript (JS) serves as the primary language for adding interactivity and
dynamic behavior to web pages. Here's an overview of JavaScript within the
project context:
23
▪ Animation and Effects: JavaScript can create animations and visual effects on
web pages using techniques like CSS animations, transitions, and
libraries/frameworks such as jQuery or GSAP (GreenSock Animation
Platform).
❖ React
React is a JavaScript library used for building user interfaces, particularly for
single-page applications (SPAs) where content is dynamically updated without
requiring full page reloads. Here's an overview of React within this project:
24
▪ JSX (JavaScript XML): React utilizes JSX, a syntax extension that allows
developers to write HTML-like code within JavaScript. JSX makes it
easier to describe UI components and their structure, combining HTML
markup with JavaScript logic seamlessly.
▪ Props (Properties): React components can receive data via props, which
are essentially read-only inputs passed from parent to child components.
Props allow for communication between components and enable
component customization and reusability.
25
▪ Component Libraries and Ecosystem: React has a rich ecosystem of third-
party libraries and tools that extend its capabilities. This includes state
management libraries like Redux, UI component libraries like Material-UI
or Ant Design, and development tools like React DevTools and Create
React App.
➢ Back-End Development
❖ Python
Python serves as the backend language, responsible for handling server-side logic,
database interactions, and API endpoints. Python serves as the backend language,
responsible for handling server-side logic, database interactions, and API
endpoints.
▪ Django Framework: The project likely uses the Django web framework, which
is a high-level Python web framework that encourages rapid development and
clean, pragmatic design. Django provides a set of built-in tools and
conventions for handling common web development tasks, such as URL
routing, database modeling, and user authentication.
▪ API Endpoints: Python code defines API endpoints using Django's `django-
rest-framework` or similar libraries. These endpoints handle incoming HTTP
requests from the frontend, perform necessary data processing or database
operations, and return appropriate HTTP responses (usually in JSON format)
containing the requested data or indicating the outcome of the request.
❖ Django
Django serves as the web framework for building the backend of the application.
Django provides a comprehensive set of tools and conventions for building web
applications quickly and efficiently. Its batteries-included approach, robust security
features, and thriving ecosystem of third-party packages make it a popular choice
for building scalable and maintainable web applications.
27
views handle the logic to process requests and generate responses, and
templates are used for rendering HTML pages.
▪ URL Routing: Django's URL dispatcher maps URL patterns to view functions
or classes, allowing developers to define how different URLs should be
handled by the application. URL patterns are typically defined in the project's
`urls.py` file and may include regular expressions or path converters to capture
dynamic parts of the URL.
▪ Forms and Validation: Django provides a forms library for handling HTML
forms and form data. Forms can be created using Python classes, and Django
handles tasks such as form rendering, data validation, and error handling
automatically. Forms can be used in views to process user input and interact
with the database.
28
Authorization can be enforced using decorators or middleware to restrict
access to certain views or resources.
▪ Static Files and Media Handling: Django provides utilities for managing static
files (e.g., CSS, JavaScript) and media files (e.g., user-uploaded images,
videos). Static files are typically served directly by the web server in
production, while media files are stored locally or on a cloud storage service
like Amazon S3.
➢ API
❖ Spotify API:
29
access token, which is used to make authenticated requests to the Spotify API
on behalf of the user.
▪ Authorization Code Flow: The application uses the authorization code flow to
authenticate users with Spotify. This flow involves redirecting the user to the
Spotify authorization page with specific parameters, including the client ID,
redirect URI, and requested scopes (permissions). After the user grants
permission, Spotify redirects back to the application with an authorization
code, which is exchanged for an access token and refresh token.
▪ Error Handling and Edge Cases: The application handles potential errors and
edge cases that may arise during interactions with the Spotify API. This
includes scenarios such as invalid access tokens, expired tokens, rate limiting,
and network errors. Error handling mechanisms ensure that the application
provides a smooth and reliable user experience even in the face of API-related
issues.
30
Scalability:
4.5.6 Appendices
Include any additional information relevant to the software requirements, such as use
case diagrams, data flow diagrams, or mockups.
31
4.6.1 Iterative Development: The project can be broken down into smaller increments or
iterations, allowing for continuous improvement and feedback throughout the development
process. Features can be implemented incrementally, with regular demonstrations to
stakeholders for feedback and validation.
4.6.4 Customer-Centric Focus: Agile places a strong emphasis on delivering value to the
customer. In this project, the customer-centric focus means prioritizing features and
functionalities that align with user needs and preferences, ensuring a positive user experience.
4.6.6 Sprint Planning: The project team conducts regular sprint planning meetings to
prioritize tasks and set goals for each iteration. This ensures that development efforts are
focused on delivering the most valuable features incrementally.
4.6.7 Daily Stand-ups: Daily stand-up meetings are held to provide a forum for team
members to discuss progress, identify any impediments, and coordinate their efforts. These
short, focused meetings help maintain alignment and address any issues promptly.
4.6.8 Iterative Feedback: Agile encourages continuous feedback loops, both from
stakeholders and end-users. Regular demos and reviews allow stakeholders to provide
feedback on the product's features and functionality, facilitating early course correction and
improvement.
32
4.6.9 Empowered Teams: Agile principles promote self-organizing, empowered teams that
take ownership of their work. Team members have the autonomy to make decisions and
adapt to changing requirements, fostering a sense of accountability and commitment to
project success.
4.6.11 Adaptive Planning: Agile methodologies recognize that requirements and priorities
may evolve over time. The project plan remains flexible, allowing for adjustments based on
feedback, changes in market conditions, or emerging opportunities.
33
4. SYSTEM DESIGN AND SPECIFICATIONS
The system design and specifications for this project outline the architecture, components,
and functionality of the collaborative music playback system. Here's an overview:
❖ Architecture:
The system follows a client-server architecture, where the server hosts the backend
logic and data storage, while the client interacts with the user through a web-based
interface.
Backend components include Django framework for server-side logic, Spotify API
integration for music playback functionality, and a PostgreSQL database for storing
user data and room information.
Frontend components utilize React.js for building interactive user interfaces and
managing state.
❖ Components:
Backend Components:
• PostgreSQL database for storing user profiles, room details, playback history, and
voting data.
Frontend Components:
• React.js for building modular UI components, managing state, and handling user
interactions.
• Material-UI library for designing responsive and visually appealing user interfaces.
• React Router for client-side routing to navigate between different views within the
application.
34
❖ Functionality:
User Authentication: Users can log in to the system using their Spotify accounts to
access the collaborative music playback features.
Room Management: Hosts can create a room and generate a unique code that other
users can use to join the room. Hosts can also set room preferences such as playback
control permissions and voting requirements.
Music Playback: Users can play, pause, skip tracks, and adjust playback volume
within the room. Playback control permissions are determined by the host's settings.
Voting System: Users can vote to skip tracks, and tracks are skipped when the
required number of votes is reached.
Real-time Updates: Hosts can update playback control settings and voting
requirements in real-time, reflecting changes immediately for all users in the room.
❖ Specifications:
System supports concurrent user sessions with efficient handling of authentication and
session management.
Integration with Spotify API ensures seamless access to music catalogs, playback
control, and user authentication.
Data storage and retrieval operations are optimized for performance and scalability,
ensuring smooth operation even under high user loads.
35
❖ SOFTWARE DESIGN
Modularity and partitioning: Software is designed such that, each system should
consists of hierarchy of modules and serve to partition into separate function.
Shared use: Avoid duplication by allowing a single module be called by other that
need the function it provides.
❖ MODULE DESIGN
Home Module
Home Module:
36
Handles the OAuth flow for obtaining user authorization.
Retrieves user profile information and access tokens for Spotify API interaction.
Displays information about the currently playing song, including the title, artist,
album cover, playback progress, and voting details.
Users can interact with the music player through buttons such as play, pause, and
skip. These buttons trigger actions to control the playback accordingly.
It also displays the number of votes each song has received for skipping
37
❖ DATABASE DESIGN
38
❖ INPUT/OUTPUT DESIGN
Input Design
The input design for the collaborative music playback system involves defining how
users interact with the application to input commands, preferences, and data. Here's an
overview of the input design:
The UI includes various input elements such as text fields, buttons, dropdowns,
and sliders.
Users interact with these elements to perform actions like logging in, creating
rooms, joining rooms, controlling playback, and voting on tracks.
o Authentication Inputs:
Input fields for users to enter their login credentials (username/email and
password) during the authentication process.
Text fields for specifying room preferences such as room name, playback
control permissions, and voting rules.
Text field for entering the room code when joining an existing room.
39
o Playback Control Inputs:
o Voting Inputs:
Output Design
The output design of the project involves presenting information and feedback to
users based on their interactions with the system. Here's an overview of the output
design elements in our collaborative music playback system:
User Interface: The system provides a user-friendly interface using React and
Material-UI components. It includes screens for different functionalities like
home, room creation, room joining, music playback, and settings.
Room Information: Upon joining a room or creating a new one, users see
relevant information such as the room code, current song details, playback
controls, and voting status.
Music Playback: The output design includes a music player interface with
controls for play, pause, and skip. It also displays the current song's title, artist,
album cover, playback progress, and voting details.
40
5.1 DATA MODEL(LIKE DFD)
A Data Flow Diagram (DFD) is a traditional visual representation of the information flows
within a system. A neat and clear DFD can depict the right amount of the system requirement
graphically. It can be manual, automated, or a combination of both.
It shows how data enters and leaves the system, what changes the information, and where
data is stored.
The objective of a DFD is to show the scope and boundaries of a system as a whole. It may
be used as a communication tool between a system analyst and any person who plays a part
in the order that acts as a starting point for redesigning a system. The DFD is also called as a
data flow graph or bubble chart.
41
➢ Source or Destination of Data: External sources or destinations of data, which
may be people or organizations or other entities.
It is also known as a context diagram. It’s designed to be an abstraction view, showing the
system as a single process with its relationship to external entities. It represents the entire
system as a single bubble with input and output data indicated by incoming/outgoing
arrows.
42
5.1.2 Level 1 DFD
This level provides a more detailed view of the system by breaking down the major
processes identified in the level 0 DFD into sub-processes. Each sub-process is depicted as
a separate process on the level 1 DFD. The data flows and data stores associated with each
sub-process are also shown.
In 1-level DFD, the context diagram is decomposed into multiple bubbles/processes. In this
level, we highlight the main functions of the system and breakdown the high-level process
of 0-level DFD into subprocesses.
43
5.2 ENTITY RELATIONSHIP MODEL
ER model stands for an Entity-Relationship model. It is a high-level data model. This model
is used to define the data elements and relationship for a specified system.
It develops a conceptual design for the database. It also develops a very simple and easy to
design view of data.
44
5.4 CLASS DIAGRAM
Class diagrams are a type of UML (Unified Modeling Language) diagram used in software
engineering to visually represent the structure and relationships of classes within a system
i.e. used to construct and visualize object-oriented systems.
45
Class diagrams provide a high-level overview of a system’s design, helping to
communicate and document the structure of the software. They are a fundamental tool in
object-oriented design and play a crucial role in the software development lifecycle.
46
5.5 STATE DIAGRAM/SEQUENCE DIAGRAM
A sequence diagram shows process interactions arranged in time sequence. This diagram
depicts the processes and objects involved and the sequence of messages exchanged as
needed to carry out the functionality.
47
5. SOURCE CODE
6.1 HTML template that provides structure to the application
<!DOCTYPE html>
<html>
<head>
<title>Tune Troop</title>
{% load static %}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<link
rel="stylesheet"
href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700&display=swap"
/>
/>
</head>
<body>
<div id="gradient">
<div id="main">
<div id="app"></div>
</div>
</div>
</body>
</html>
48
6.2 CSS for styling
html,
body {
height: 100%;
margin: 0;
padding: 0;
#main {
position: fixed;
width: 100%;
height: 100%;
left: 0;
top: 0;
#app {
width: 100%;
height: 100%;
.center {
position: absolute;
top: 50%;
left: 50%;
#gradient {
49
width: 100%;
height: 800px;
padding: 0px;
margin: 0px;
[62,35,255],
[60,255,60],
[255,35,98],
[45,175,230],
[255,0,255],
[255,128,0]);
var step = 0;
//transition speed
function updateGradient()
50
{
if ( $===undefined ) return;
$('#gradient').css({
step += gradientSpeed;
if ( step >= 1 )
step %= 1;
51
colorIndices[0] = colorIndices[1];
colorIndices[2] = colorIndices[3];
setInterval(updateGradient,10);
import string
import random
def generate_unique_code():
length = 6
while True:
if Room.objects.filter(code=code).count() == 0:
break
return code
52
class Room(models.Model):
code = models.CharField(
created_at = models.DateTimeField(auto_now_add=True)
6.5 Creation of serializers for the ‘Room’ model in the Django REST
Framework
from rest_framework import serializers
class RoomSerializer(serializers.ModelSerializer):
class Meta:
model = Room
'votes_to_skip', 'created_at')
class CreateRoomSerializer(serializers.ModelSerializer):
class Meta:
model = Room
class UpdateRoomSerializer(serializers.ModelSerializer):
code = serializers.CharField(validators=[])
53
class Meta:
model = Room
fields = ('guest_can_pause', 'votes_to_skip', 'code')
class RoomView(generics.ListAPIView):
queryset = Room.objects.all()
serializer_class = RoomSerializer
class GetRoom(APIView):
serializer_class = RoomSerializer
lookup_url_kwarg = 'code'
code = request.GET.get(self.lookup_url_kwarg)
if code != None:
room = Room.objects.filter(code=code)
if len(room) > 0:
data = RoomSerializer(room[0]).data
54
return Response(data, status=status.HTTP_200_OK)
class JoinRoom(APIView):
lookup_url_kwarg = 'code'
if not self.request.session.exists(self.request.session.session_key):
self.request.session.create()
code = request.data.get(self.lookup_url_kwarg)
if code != None:
room_result = Room.objects.filter(code=code)
if len(room_result) > 0:
room = room_result[0]
self.request.session['room_code'] = code
return Response({'Bad Request': 'Invalid post data, did not find a code key'},
status=status.HTTP_400_BAD_REQUEST)
class CreateRoomView(APIView):
serializer_class = CreateRoomSerializer
55
def post(self, request, format=None):
if not self.request.session.exists(self.request.session.session_key):
self.request.session.create()
serializer = self.serializer_class(data=request.data)
if serializer.is_valid():
guest_can_pause = serializer.data.get('guest_can_pause')
votes_to_skip = serializer.data.get('votes_to_skip')
host = self.request.session.session_key
queryset = Room.objects.filter(host=host)
if queryset.exists():
room = queryset[0]
room.guest_can_pause = guest_can_pause
room.votes_to_skip = votes_to_skip
room.save(update_fields=['guest_can_pause', 'votes_to_skip'])
self.request.session['room_code'] = room.code
else:
votes_to_skip=votes_to_skip)
room.save()
self.request.session['room_code'] = room.code
class UserInRoom(APIView):
56
def get(self, request, format=None):
if not self.request.session.exists(self.request.session.session_key):
self.request.session.create()
data = {
'code': self.request.session.get('room_code')
class LeaveRoom(APIView):
if 'room_code' in self.request.session:
self.request.session.pop('room_code')
host_id = self.request.session.session_key
room_results = Room.objects.filter(host=host_id)
if len(room_results) > 0:
room = room_results[0]
room.delete()
class UpdateRoom(APIView):
serializer_class = UpdateRoomSerializer
if not self.request.session.exists(self.request.session.session_key):
self.request.session.create()
serializer = self.serializer_class(data=request.data)
57
if serializer.is_valid():
guest_can_pause = serializer.data.get('guest_can_pause')
votes_to_skip = serializer.data.get('votes_to_skip')
code = serializer.data.get('code')
queryset = Room.objects.filter(code=code)
if not queryset.exists():
room = queryset[0]
user_id = self.request.session.session_key
if room.host != user_id:
room.guest_can_pause = guest_can_pause
room.votes_to_skip = votes_to_skip
room.save(update_fields=['guest_can_pause', 'votes_to_skip'])
58
urlpatterns = [
path('room', RoomView.as_view()),
path('create-room', CreateRoomView.as_view()),
path('get-room', GetRoom.as_view()),
path('join-room', JoinRoom.as_view()),
path('user-in-room', UserInRoom.as_view()),
path('leave-room', LeaveRoom.as_view()),
path('update-room', UpdateRoom.as_view())
constructor(props) {
super(props);
render() {
return (
<div className="center">
<HomePage />
</div>
);
59
const appDiv = document.getElementById("app");
import { BrowserRouter as Router, Routes, Route, Link, Redirect, Navigate } from 'react-
router-dom';
constructor(props){
super(props);
this.state={
roomCode: null,
};
this.clearRoomCode=this.clearRoomCode.bind(this);
async componentDidMount(){
fetch('/api/user-in-room')
.then((response)=>response.json()).
then((data)=>{
this.setState({
roomCode:data.code,
});
});
60
}
renderHomePage(){
if(this.state.roomCode){
return(
);
}else{
return(
Tune Troop
</Typography>
</Grid>
Create a Room
</Button>
Join a Room
</Button>
</ButtonGroup>
</Grid>
</Grid>
);
61
clearRoomCode(){
this.setState({
roomCode:null,
});
render(){
return (<Router>
<Routes>
/>
</Route>
</Routes>
</Router>);
62
import {FormHelperText} from "@mui/material";
function CreateRoomPage(props){
const navigate=useNavigate();
const[guestCanPause,setguestCanPause]=useState(props.guestCanPause);
const[votesToSkip,setgvotesToSkip]=useState(props.votesToSkip);
const[errorMsg,setErrorMsg]=useState("");
const[successMsg,setSuccessMsg]=useState("");
const handleVotesChange=()=>{
setgvotesToSkip(event.target.value);
};
const handleGuestCanPauseChange=()=>{
setguestCanPause(event.target.value==="true"?true:false);
};
const handleRoomButtonPressed=()=>{
const requestOptions = {
method: 'POST',
63
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({
votes_to_skip:votesToSkip,
guest_can_pause:guestCanPause,
}),
};
fetch('/api/create-room', requestOptions)
.then((response)=>response.json())
};
const handleUpdateButtonPressed=()=>{
const requestOptions = {
method: 'PATCH',
body: JSON.stringify({
votes_to_skip:votesToSkip,
guest_can_pause:guestCanPause,
code:props.roomCode,
}),
};
fetch('/api/update-room', requestOptions)
.then((response)=>{
if(response.ok){
}else{
props.updateCallback();
64
});
};
const renderCreateButtons=()=>{
return(
</Grid>
</Grid>
</Grid>
);
};
const renderUpdateButtons=()=>{
return(
</Grid>
</Grid>
);
};
65
const title=props.update? "Update Room" : "Create a Room";
return (
{successMsg!=""?(
<Alert
severity="success"
onClose={()=>{
setSuccessMsg("");
}}>
{successMsg}
</Alert>
):(
<Alert
severity="error"
onClose={()=>{
setErrorMsg("");
}}>
{errorMsg}
</Alert>
)}
</Collapse>
</Grid>
{title}
</Typography>
66
</Grid>
<FormControl component="fieldset">
<FormHelperText component="div">
</FormHelperText>
labelPlacement="bottom"></FormControlLabel>
</RadioGroup>
</FormControl>
</Grid>
<FormControl>
inputProps={{min:1, style:{textAlign:"center"},}}></TextField>
<FormHelperText component="div">
<div align="center">
</div>
</FormHelperText>
</FormControl>
67
</Grid>
{props.update?renderUpdateButtons(): renderCreateButtons()}
</Grid>
);
CreateRoomPage.defaultProps={
votesToSkip:2,
guestCanPause:true,
update: false,
roomCode:null,
updateCallback:()=>{},
};
const navigate=useNavigate();
const[roomCode, setroomCode]=useState('');
const[errorMsg,seterrorMsg]=useState('');
const[error,seterror]=useState(false);
const handleTextFieldChange=()=>{
68
setroomCode(event.target.value);
};
const roomButtonPressed=()=>{
const requestOptions={
method: "POST",
headers:{"Content-Type": "application/json"},
body:JSON.stringify({
code:roomCode,
}),
};
fetch("/api/join-room",requestOptions).
then((response)=>{
if(response.ok){
navigate("/room/"+ roomCode)
}else{
seterror(true);
})
.catch((error)=>{
console.log(error);
});
};
return(
Join a Room
69
</Typography>
</Grid>
<TextField
error={error}
label="Code"
value={roomCode}
helperText={errorMsg}
variant='outlined'
onChange={handleTextFieldChange}>
</TextField>
</Grid>
<Button
variant='contained'
color='primary'
onClick={roomButtonPressed}>
Enter Room
</Button>
</Grid>
<Button variant='contained'
Back
</Button>
</Grid>
</Grid>
70
);
function Room(props){
const navigate=useNavigate();
const{roomCode}=useParams()
const initialState={
votesToSkip:2,
guestCanPause:false,
isHost:false,
showSettings: false,
spotifyAuthenticated: false,
song:{},
}
const[roomData, setRoomData]=useState(initialState)
useEffect(() => {
getRoomDetails();
return ()=>clearInterval(interval);
},[roomCode]);
71
const getRoomDetails = () => {
.then((response) => {
if (!response.ok) {
props.clearRoomCodeCallback();
navigate("/");
return response.json();
})
.then((data) => {
setRoomData(prevState=>({
...prevState,
votesToSkip: data.votes_to_skip,
guestCanPause: data.guest_can_pause,
isHost: data.is_host
}));
if(data.is_host){
authenticateSpotify();
});
};
const authenticateSpotify=()=>{
fetch("/spotify/is-authenticated")
.then((data) => {
console.log(data.status);
if (!data.status) {
72
fetch("/spotify/get-auth-url")
.then((data) => {
window.location.replace(data.url);
});
});
};
fetch('/spotify/current-song')
.then((response) => {
if (!response.ok) {
return {};
} else {
return response.json();
})
.then((data) => {
console.log(data);
});
};
const leaveButtonPressed=()=>{
const requestOptions={
method: "POST",
headers:{"Content-Type": "application/json"},
};
73
fetch('/api/leave-room',requestOptions).
then((response)=>{
props.clearRoomCodeCallback();
navigate('/');
});
};
const updateShowSettings=(value)=>{
setRoomData({
...roomData,
showSettings:value,
});
};
const renderSettings=()=>{
return(
<Grid container spacing={1}>
<CreateRoomPage
update={true}
votesToSkip={roomData.votesToSkip}
guestCanPause={roomData.guestCanPause}
roomCode={roomCode}
updateCallback={getRoomDetails}
getRoomDetails={getRoomDetails}
/>
</Grid>
<Button
74
variant='contained'
color='secondary'
onClick={()=>updateShowSettings(false)}
>
Close
</Button>
</Grid>
</Grid>
);
};
const renderSettingsButton=()=>{
return(
Settings
</Button>
</Grid>
);
};
return roomData.showSettings?(
renderSettings()
):(
75
Code:{roomCode}
</Typography>
</Grid>
<MusicPlayer {...roomData.song}/>
{roomData.isHost?renderSettingsButton():null}
Leave Room
</Button>
</Grid>
</Grid>
Grid,
Typography,
Card,
IconButton,
LinearProgress,
} from '@mui/material';
76
const requestOptions = {
method: "POST",
headers: { "Content-Type": "application/json" },
};
fetch("/spotify/skip", requestOptions);
};
const requestOptions = {
method: "PUT",
headers: { "Content-Type": "application/json" },
};
fetch("/spotify/pause", requestOptions);
};
const requestOptions = {
method: "PUT",
headers: { "Content-Type": "application/json" },
};
fetch("/spotify/play", requestOptions);
};
return (
<Card>
</Grid>
77
<Grid item align="center" xs={8}>
{props.title}
</Typography>
{props.artist}
</Typography>
<div>
{props.is_playing ? <Pause></Pause> :
<PlayArrowRounded></PlayArrowRounded>}
</IconButton>
<IconButton onClick={()=>skipSong()}>
{props.votes}/{" "}{props.votes_required}
<SkipNext></SkipNext>
</IconButton>
</div>
</Grid>
</Grid>
</Card>
);
};
78
6.14 Django model for storing Spotify authentication tokens and user votes
from django.db import models
class SpotifyToken(models.Model):
created_at = models.DateTimeField(auto_now_add=True)
refresh_token = models.CharField(max_length=150)
access_token = models.CharField(max_length=150)
expires_in = models.DateTimeField()
token_type = models.CharField(max_length=50)
class Vote(models.Model):
created_at = models.DateTimeField(auto_now_add=True)
song_id = models.CharField(max_length=50)
REDIRECT_URI = "http://127.0.0.1:8000/spotify/redirect"
79
from rest_framework.response import Response
class AuthURL(APIView):
'scope': scopes,
'response_type': 'code',
'redirect_uri': REDIRECT_URI,
'client_id': CLIENT_ID
}).prepare().url
code = request.GET.get('code')
error = request.GET.get('error')
'grant_type': 'authorization_code',
'code': code,
'redirect_uri': REDIRECT_URI,
'client_id': CLIENT_ID,
'client_secret': CLIENT_SECRET
80
}).json()
access_token = response.get('access_token')
token_type = response.get('token_type')
refresh_token = response.get('refresh_token')
expires_in = response.get('expires_in')
error = response.get('error')
if not request.session.exists(request.session.session_key):
request.session.create()
update_or_create_user_tokens(
return redirect('frontend:')
class IsAuthenticated(APIView):
is_authenticated = is_spotify_authenticated(
self.request.session.session_key)
class CurrentSong(APIView):
room_code = self.request.session.get('room_code')
room = Room.objects.filter(code=room_code)
if room.exists():
room = room[0]
else:
81
return Response({}, status=status.HTTP_404_NOT_FOUND)
host = room.host
endpoint = "player/currently-playing"
item = response.get('item')
duration = item.get('duration_ms')
progress = response.get('progress_ms')
album_cover = item.get('album').get('images')[0].get('url')
is_playing = response.get('is_playing')
song_id = item.get('id')
artist_string = ""
if i > 0:
name = artist.get('name')
artist_string += name
song = {
'title': item.get('name'),
'artist': artist_string,
'duration': duration,
'time': progress,
82
'image_url': album_cover,
'is_playing': is_playing,
'votes': votes,
'votes_required': room.votes_to_skip,
'id': song_id
self.update_room_song(room, song_id)
current_song = room.current_song
if current_song != song_id:
room.current_song = song_id
room.save(update_fields=['current_song'])
votes = Vote.objects.filter(room=room).delete()
class PauseSong(APIView):
room_code = self.request.session.get('room_code')
room = Room.objects.filter(code=room_code)[0]
pause_song(room.host)
83
class PlaySong(APIView):
room_code = self.request.session.get('room_code')
room = Room.objects.filter(code=room_code)[0]
play_song(room.host)
return Response({}, status=status.HTTP_204_NO_CONTENT)
class SkipSong(APIView):
room_code = self.request.session.get('room_code')
room = Room.objects.filter(code=room_code)[0]
votes_needed = room.votes_to_skip
votes.delete()
skip_song(room.host)
else:
vote = Vote(user=self.request.session.session_key,
room=room, song_id=room.current_song)
vote.save()
84
6.17 To handle Spotify authentication and integration using Spotify API
from .models import SpotifyToken
BASE_URL = "https://api.spotify.com/v1/me/"
def get_user_tokens(session_id):
user_tokens = SpotifyToken.objects.filter(user=session_id)
if user_tokens.exists():
return user_tokens[0]
else:
return None
tokens = get_user_tokens(session_id)
if tokens:
tokens.access_token = access_token
tokens.refresh_token = refresh_token
tokens.expires_in = expires_in
tokens.token_type = token_type
tokens.save(update_fields=['access_token',
'refresh_token', 'expires_in', 'token_type'])
85
else:
refresh_token=refresh_token, token_type=token_type,
expires_in=expires_in)
tokens.save()
def is_spotify_authenticated(session_id):
tokens = get_user_tokens(session_id)
if tokens:
expiry = tokens.expires_in
refresh_spotify_token(session_id)
return True
return False
def refresh_spotify_token(session_id):
refresh_token = get_user_tokens(session_id).refresh_token
'grant_type': 'refresh_token',
'refresh_token': refresh_token,
'client_id': CLIENT_ID,
'client_secret': CLIENT_SECRET
}).json()
access_token = response.get('access_token')
token_type = response.get('token_type')
86
expires_in = response.get('expires_in')
update_or_create_user_tokens(
tokens = get_user_tokens(session_id)
if post_:
if put_:
try:
return response.json()
except:
return {'Error': 'Issue with request'}
def play_song(session_id):
def pause_song(session_id):
def skip_song(session_id):
87
6.18 URL patterns for the API views
from django.urls import path
urlpatterns = [
path('get-auth-url', AuthURL.as_view()),
path('redirect', spotify_callback),
path('is-authenticated', IsAuthenticated.as_view()),
path('current-song', CurrentSong.as_view()),
path('pause', PauseSong.as_view()),
path('play', PlaySong.as_view()),
path('skip', SkipSong.as_view())
6.19 URL pattern to include URLS from different parts of the application
from django.contrib import admin
urlpatterns = [
path('admin/', admin.site.urls),
path('api/', include('api.urls')),
path('', include('frontend.urls')),
path('spotify/', include('spotify.urls'))
88
6. SCREENSHOT
89
7.3 SPOTIFY ACCOUNT LOGIN PAGE
90
7.5 UPDATE ROOM PAGE
91
7.5 MUSIC PLAYER PAGE FOR GUEST
92
7. TESTING
Software testing can be stated as the process of verifying and validating whether a software
or application is bug-free, meets the technical requirements as guided by its design and
development, and meets the user requirements effectively and efficiently by handling all
the exceptional and boundary cases.
The purpose of software testing is to identify the errors, faults, or missing requirements in
contrast to actual requirements. It mainly aims at measuring the specification, functionality,
and performance of a software program or application.
Validation: Ensure that the software meets the specified requirements and fulfills its
intended purpose effectively and accurately.
Verification: Confirm that the software conforms to its design specifications and
standards, ensuring consistency and reliability in its behavior.
Identification of Defects: Detect and identify any defects, bugs, or errors in the
software early in the development process to prevent them from impacting the end-
users or causing issues in production.
Quality Assurance: Ensure that the software meets predefined quality standards,
including functionality, performance, security, usability, and maintainability.
Risk Mitigation: Identify and mitigate potential risks associated with the software,
such as security vulnerabilities, performance bottlenecks, and usability issues, to
minimize their impact on the end-users and the organization.
93
Compliance: Ensure that the software complies with relevant laws, regulations,
standards, and industry best practices, such as accessibility standards, data privacy
regulations, and security guidelines.
Cost Reduction: Identify and eliminate defects and inefficiencies early in the
development lifecycle to reduce the overall cost of software development,
maintenance, and support.
System Testing: Test the entire system as a whole to verify that it meets the specified
requirements and functions correctly in its intended environment.
Acceptance Testing: Test the software from the end-user's perspective to determine if
it meets their needs and expectations.
Regression Testing: Test previously implemented features to ensure they still function
correctly after new changes or updates are made.
Security Testing: Identify and mitigate potential security vulnerabilities and threats to
protect the software and its users' data.
94
ACKNOWLEDGEMENT
We express our sincere gratitude to Prof. Satya Narayan Das, Head of The Department of
Computer Science and Applications for allowing me to accomplish the project. With his
active support and guidance, this project report has been completed.
We also thank Mr. Ashutosh Mallik our Project Coordinator for guidance and help.
We also thank Mrs. Sucheta Krupalini Moharana our Project Supervisor for guidance and help.
Page Number
Abstract 1
1. Introduction 2-4
1.1 Purpose 2
1.2 Project Scope 2
1.3 Project Features 3-4
2. Literature Review 5-7
3. Problem Statement 8-10
4. System Analysis 11-33
4.1 Identification of Need 11
4.2 Preliminary Investigation 12-13
4.3 Feasibility Study 13 -14
4.4 Project Planning 15-17
4.5 Software Requirement Specifications (SRS) 17-31
4.6 Software Engineering Paradigm Applied 31-33
5. System Design &Specifications 34-47
5.1 Data models (like DFD) 41-43
5.2 Entity Relationship Model 44
5.3 Use-case Diagrams 44-45
5.4 Class Diagrams 45-46
5.5 State Diagrams/Sequence Diagrams 47
6. Source Code 48-88
7. Screenshots 89-92
8. Testing 93-100
8.1 Testing Techniques and Testing Strategies Used Testing Plan used 94-96
8.2 Test Reports for Unit Test Cases and System Test Cases 96-100
9. Conclusion 101-102
10. Future Enhancement 103-105
11. References / Bibliography 106
ABSTRACT
Title: Development of an E-STORE Using Python, D jango, HTML, CSS, and Bootstrap
Abstract:
In today's digital age, online shopping has become increasingly popular, especially for
essential items like groceries. This project aims to develop a comprehensive online
grocery shop using Python, Django, HTML, CSS, and Bootstrap.
The system will provide users with a convenient platform to browse through a wide
range of grocery products, add them to their cart, and securely complete their purchases.
The backend will be powered by Django, a high-level Python web framework, which
will handle user authentication, product management, order processing, and database
interactions.
The frontend will be developed using HTML, CSS, and Bootstrap to create a visually
appealing and responsive user interface. Bootstrap's grid system and components will
ensure that the website is accessible across various devices and screen sizes, providing a
seamless shopping experience for users on desktops, laptops, tablets, and smartphones.
Key features of the online grocery shop will include user registration and login, product
categorization and search functionality, product details and images, shopping cart
management, secure payment processing integration, order tracking, and email
notifications.
Overall, this project aims to leverage modern web development technologies to create
an efficient and user-friendly online grocery shopping platform, catering to the needs of
today's digitally savvy consumers.
1
INTRODUCTION
PURPOSE :
2
PROJECT FEATURES :
Here's a breakdown of the project features for the online grocery shop developed using Python,
Django, HTML, CSS, and Bootstrap:
1. User Registration and Authentication:
- Allow users to register with the platform by providing necessary details.
- Implement authentication mechanisms to ensure secure access to user accounts.
- Enable users to log in and log out of their accounts securely.
2. Product Management:
- Provide functionality for administrators to add, edit, and delete grocery products.
- Include fields such as product name, description, price, quantity, and images.
- Implement product categorization and tagging for easy navigation.
3. Browsing and Searching:
- Enable users to browse through the available grocery products conveniently.
- Implement search functionality to allow users to find specific products quickly.
- Provide filtering options based on categories, prices, and other attributes.
4. Shopping Cart Management:
- Allow users to add products to their shopping carts while browsing.
- Provide options to update the quantity or remove items from the cart.
- Display the total cost and summary of items in the shopping cart.
5. Checkout Process:
- Implement a streamlined checkout process for users to complete their purchases.
- Include forms for users to provide shipping and billing information.
- Integrate secure payment gateways for processing transactions (e.g., PayPal, Stripe).
3
1.1.1 Error Handling and Security: Robust error handling mechanisms and security
measures are implemented to ensure data integrity, user privacy, and protection against
unauthorized access.
4
1. LITERATURE REVIEW
Collaborative music playback systems have emerged as a novel way for users to engage with
music in shared listening experiences. These systems enable multiple users to synchronize
their music playback across devices, allowing for collaborative playlist creation, voting on
tracks, and real-time interaction. This literature review aims to provide a comprehensive
overview of existing research and developments in collaborative music playback systems,
focusing on design principles, technical implementations, user experiences, and the social
impact of these systems.
Looking ahead, future research directions in collaborative music playback systems may
include exploring novel interaction paradigms, integrating emerging technologies like virtual
reality and spatial audio, and investigating the social and cultural implications of shared
6
listening experiences. Moreover, interdisciplinary collaborations between researchers,
designers, musicians, and industry stakeholders can lead to innovative solutions that redefine
how people discover, share, and enjoy music together in the digital age.
7
2. PROBLEM STATEMENT
The problem statement for the project revolves around the need for a collaborative music
playback system that allows multiple users to join a virtual room, synchronize playback, and
control music playback together. Existing music streaming platforms lack real-time
collaboration features, limiting the ability for users to enjoy music together simultaneously.
Therefore, there is a need to develop a platform that enables users to create and join rooms,
interact with other users in real-time, and collectively control music playback. This project
aims to address these limitations by implementing features such as room creation, user
authentication through Spotify, real-time synchronization of playback, and control of
playback features by both hosts and guests.
3.1.2 User Authentication and Integration with Spotify API: Integrating user
authentication via Spotify and leveraging the Spotify API to retrieve and control music
playback requires handling OAuth flows securely and managing access tokens effectively.
3.1.3 Room Management and Data Consistency: Managing rooms dynamically, including
creation, joining, and leaving, while maintaining data consistency and integrity across
connected users presents challenges in database design and synchronization.
3.1.4 Playback Control Permissions: Implementing logic to allow hosts to control playback
permissions for guests, such as play, pause, and skip, requires robust authorization
mechanisms.
3.1.5 Real-Time Updates and Notifications: Enabling real-time updates for playback
control and room settings poses challenges in handling WebSocket communications and
ensuring efficient event propagation.
8
3.1.6 Error Handling and Resilience: Implementing robust error handling mechanisms to
address potential failures in API calls, user authentication, or real-time synchronization is
essential for maintaining a seamless user experience.
• Utilize efficient data structures and algorithms for managing playback state and
ensuring synchronized playback experiences.
• Implement OAuth 2.0 authentication flow securely to authenticate users with their
Spotify accounts.
• Utilize Spotify API endpoints to retrieve user-specific music data, control playback,
and manage user permissions.
• Design a robust database schema to manage rooms, users, and playback state
efficiently.
• Implement role-based access control (RBAC) mechanisms to manage user roles (host
vs. guest) and permissions for controlling playback.
9
3.2.5 Real-Time Updates and Notifications
• Implement robust error handling mechanisms to gracefully handle errors and failures
in API calls, authentication flows, and real-time communication.
• Utilize logging and monitoring tools to track and diagnose errors in real-time,
ensuring quick resolution and minimal disruption to the user experience.
10
3. SYSTEM ANALYSIS
• With the increasing popularity of music streaming services like Spotify, there's a
growing demand for collaborative music playback systems that allow users to listen
to music together in real-time.
• Many users enjoy listening to music with friends or family members, whether they're
in the same location or miles apart. A collaborative music playback system fulfills
the need for shared music listening experiences.
• With the rise of virtual events and gatherings, there's a need for platforms that enable
participants to listen to music together during online parties, virtual hangouts, or
remote celebrations.
• In remote work and learning environments, collaborative music playback systems can
serve as icebreakers, team-building tools, or background entertainment during
virtual meetings and study sessions.
• Users often have diverse musical preferences and tastes. A collaborative music
playback system allows users to share and discover music based on their individual
preferences, creating personalized listening experiences.
11
4.2 PRELIMINARY INVESTIGATION:
The preliminary investigation of this project involves cconducting initial research and
analysis to gather information and assess the feasibility of the project. It includes the
following steps:
• Clarify the project's goals and objectives, such as developing a collaborative music
playback system, integrating with the Spotify API, enabling real-time
synchronization of playback, and providing user-friendly interfaces.
• Assess the technical feasibility of implementing the project, considering factors such
as available resources (e.g., technology stack, development tools), integration with
third-party APIs (e.g., Spotify), and scalability requirements.
• Determine the resources needed for the project, including personnel, time, budget,
hardware, and software. Allocate resources effectively to ensure successful project
execution.
12
4.2.7 Risk Assessment
• Identify potential risks and challenges associated with the project, such as technical
complexities, data security concerns, regulatory compliance, and dependencies on
external factors (e.g., API changes).
• Evaluate the costs and benefits of implementing the project, considering factors such
as development costs, potential revenue streams, market demand, competitive
advantage, and long-term sustainability.
• Assess the technical requirements of integrating with the Spotify API and
implementing real-time synchronization of playback across multiple users.
• Evaluate the compatibility of chosen technologies (Python, Django, React) with the
project requirements.
• Compare the projected costs with the budget allocated for the project to ensure
financial viability.
13
4.3.3 Operational Feasibility
• Evaluate the operational aspects of the project, including how it will be managed,
maintained, and supported post-launch.
• Assess the availability of skilled personnel to develop, deploy, and maintain the
application.
• Consider scalability requirements and whether the project can accommodate growth
in user base and usage over time.
• Identify any legal or regulatory requirements related to music streaming, user data
privacy, copyright, and licensing.
• Ensure compliance with relevant laws and regulations to avoid legal issues and
penalties.
• Analyze the market demand for collaborative music playback systems and the
potential user base for the application.
• Determine if the project fills a gap in the market and offers unique features or
advantages compared to existing solutions.
• Consider any dependencies, constraints, or risks that may impact the project schedule.
• Ensure that the proposed timeline aligns with stakeholders' expectations and business
objectives.
14
4.4 PROJECT PLANNING
Project planning for this collaborative music playback system involves organizing tasks,
allocating resources, and establishing timelines to ensure successful development and
deployment. Here's an outline of the project planning process:
• Clearly articulate the goals and objectives of the project, including the features and
functionality of the collaborative music playback system.
• Break down the project into smaller, manageable tasks and subtasks.
• Estimate the time required to complete each task based on factors such as complexity,
dependencies, and available resources.
• Create a project timeline or Gantt chart that outlines the sequence of tasks, milestones,
and deadlines.
• Identify potential risks and uncertainties that may impact the project schedule, budget,
or quality.
• Develop strategies to mitigate risks and minimize their impact on the project.
15
• Establish contingency plans to address unforeseen challenges that may arise during
development.
• Assign roles and responsibilities to team members based on their skills, expertise, and
availability.
• Regularly monitor project progress against the established schedule and milestones.
• Track resource utilization, budget expenditures, and any deviations from the plan.
• Implement corrective actions as needed to keep the project on track and address any
issues or delays.
• Solicit feedback and address any concerns to ensure stakeholder satisfaction and
alignment with project goals.
• Conduct a post-project review to assess the overall success of the collaborative music
playback system. Evaluate the project against its original objectives, budget, and
schedule.
16
• Prepare a formal project closure report summarizing the project's outcomes,
achievements, and recommendations for future improvements.
4.5.1 Introduction
• User Management
• Music Playback
• Users can play, pause, skip, and control playback of music tracks.
• Real-time Synchronization
• Music playback is synchronized across all connected users in the same room.
• Voting System
• Users can vote to skip tracks, with the option for hosts to set the minimum
number of votes required.
17
• Room Management
• Hosts can close the room, preventing new participants from joining.
• User Interaction
• Users can chat with other participants in the same room, enhancing social
interaction.
• Playback History
• The system maintains a playback history for each room, allowing users to
view previously played tracks and their associated metadata.
• Guest Permissions
• Playlist Management
• Users can create and manage playlists within the application, adding or
removing tracks from their personal collection.
• Hosts can create shared playlists for the entire room to collaborate on.
• Performance
• Security
• Reliability
• Usability
• It should provide feedback and guidance to users as they interact with the
system.
• Accessibility
• Scalability
• The system should adhere to data privacy regulations such as GDPR (General
Data Protection Regulation).
19
• User consent mechanisms should be implemented for data collection and
processing activities.
• Logs should be generated for system events, user actions, and error conditions,
aiding in troubleshooting and auditing.
Spotify API
• Integration with the Spotify API for music playback and user authentication.
Frontend Interface
Database Interface
• Interaction with the database to store user information, room settings, and playback
data.
4.5.5 Constraints
Technology Stack
➢ Front-End Development
HTML, or Hypertext Markup Language, is the standard language used to create and
design web pages. It provides the structure for web content by using various tags and
attributes to define elements on a page. HTML is the backbone of web development,
providing the foundation for creating visually appealing and interactive web pages. It
works hand in hand with CSS (Cascading Style Sheets) for styling and JavaScript for
interactivity, forming the core technologies of the World Wide Web.
20
Overview of HTML
▪ Tags: HTML is built on tags, which are enclosed in angle brackets `< >`. Tags
are used to define different types of content on a webpage, such as headings,
paragraphs, images, links, and more.
▪ Elements: HTML elements are made up of tags and the content they surround.
For example, a paragraph element `<p>` starts with an opening tag and ends with
a closing tag `</p>`, enclosing the paragraph text.
▪ Attributes: Tags can have attributes that provide additional information about an
element. Attributes are placed within the opening tag and typically come inname-
value pairs, such as `href` in an anchor tag `<a href="https://example.com">`.
▪ HTML: The HTML element (`<html>`) is the root element of an HTML page. It
wraps all the content on the page.
▪ Head: The head element (`<head>`) contains metadata and links to external
resources used by the HTML document. It doesn't display any content directly to
the user.
▪ Meta: The meta element (`<meta>`) is used to provide metadata about the HTML
document. Common uses include specifying the character encoding (`charset`
attribute) and setting the viewport for responsive design (`viewport` attribute).
21
▪ Title: The title element (`<title>`) sets the title of the HTML document, which is
displayed in the browser's title bar or tab. It's also used by search engines for page
indexing and in bookmarks.
▪ Div: The div element (`<div>`) is a generic container used to group and style
HTML elements. It's often used to create sections or divisions within a webpage
and is styled using CSS.
▪ Body: The body element (`<body>`) contains the content of the HTML document
that's displayed to the user. It includes text, images, links, forms, and other
elements that make up the visible part of the webpage.
CSS (Cascading Style Sheets) is a language used for describing the presentation
of a document written in HTML (HyperText Markup Language). Here's an overview
of CSS:
▪ Selectors: CSS selectors are patterns used to select the elements you want to
style. They can select elements based on their tag name, class, ID, attributes, and
more. They are a fundamental part of CSS syntax and play a crucial role in
styling web pages.
▪ Properties and Values: CSS properties are the styling attributes you can apply to
selected elements. Each property has a specific value associated with it that
defines how the property should be applied. Examples of properties include
`color`, `font-size`, `background-color`, `margin`, `padding`, and `border`.
▪ Cascading: CSS stands for "Cascading" Style Sheets, which refers to the way
styles are applied to elements. Styles can be inherited from parent elements,
overridden by more specific selectors, or overwritten by inline styles.
▪ Units: CSS supports different units of measurement for specifying sizes and
distances, such as pixels (`px`), percentages (`%`), ems (`em`), rems (`rem`), and
viewport units (`vw`, `vh`, `vmin`, `vmax`).
22
❖ JavaScript
JavaScript (JS) serves as the primary language for adding interactivity and
dynamic behavior to web pages. Here's an overview of JavaScript within the
project context:
23
▪ Animation and Effects: JavaScript can create animations and visual effects on
web pages using techniques like CSS animations, transitions, and
libraries/frameworks such as jQuery or GSAP (GreenSock Animation
Platform).
❖ React
React is a JavaScript library used for building user interfaces, particularly for
single-page applications (SPAs) where content is dynamically updated without
requiring full page reloads. Here's an overview of React within this project:
24
▪ JSX (JavaScript XML): React utilizes JSX, a syntax extension that allows
developers to write HTML-like code within JavaScript. JSX makes it
easier to describe UI components and their structure, combining HTML
markup with JavaScript logic seamlessly.
▪ Props (Properties): React components can receive data via props, which
are essentially read-only inputs passed from parent to child components.
Props allow for communication between components and enable
component customization and reusability.
25
▪ Component Libraries and Ecosystem: React has a rich ecosystem of third-
party libraries and tools that extend its capabilities. This includes state
management libraries like Redux, UI component libraries like Material-UI
or Ant Design, and development tools like React DevTools and Create
React App.
➢ Back-End Development
❖ Python
Python serves as the backend language, responsible for handling server-side logic,
database interactions, and API endpoints. Python serves as the backend language,
responsible for handling server-side logic, database interactions, and API
endpoints.
▪ Django Framework: The project likely uses the Django web framework, which
is a high-level Python web framework that encourages rapid development and
clean, pragmatic design. Django provides a set of built-in tools and
conventions for handling common web development tasks, such as URL
routing, database modeling, and user authentication.
▪ API Endpoints: Python code defines API endpoints using Django's `django-
rest-framework` or similar libraries. These endpoints handle incoming HTTP
requests from the frontend, perform necessary data processing or database
operations, and return appropriate HTTP responses (usually in JSON format)
containing the requested data or indicating the outcome of the request.
❖ Django
Django serves as the web framework for building the backend of the application.
Django provides a comprehensive set of tools and conventions for building web
applications quickly and efficiently. Its batteries-included approach, robust security
features, and thriving ecosystem of third-party packages make it a popular choice
for building scalable and maintainable web applications.
27
views handle the logic to process requests and generate responses, and
templates are used for rendering HTML pages.
▪ URL Routing: Django's URL dispatcher maps URL patterns to view functions
or classes, allowing developers to define how different URLs should be
handled by the application. URL patterns are typically defined in the project's
`urls.py` file and may include regular expressions or path converters to capture
dynamic parts of the URL.
▪ Forms and Validation: Django provides a forms library for handling HTML
forms and form data. Forms can be created using Python classes, and Django
handles tasks such as form rendering, data validation, and error handling
automatically. Forms can be used in views to process user input and interact
with the database.
28
Authorization can be enforced using decorators or middleware to restrict
access to certain views or resources.
▪ Static Files and Media Handling: Django provides utilities for managing static
files (e.g., CSS, JavaScript) and media files (e.g., user-uploaded images,
videos). Static files are typically served directly by the web server in
production, while media files are stored locally or on a cloud storage service
like Amazon S3.
➢ API
❖ Spotify API:
29
access token, which is used to make authenticated requests to the Spotify API
on behalf of the user.
▪ Authorization Code Flow: The application uses the authorization code flow to
authenticate users with Spotify. This flow involves redirecting the user to the
Spotify authorization page with specific parameters, including the client ID,
redirect URI, and requested scopes (permissions). After the user grants
permission, Spotify redirects back to the application with an authorization
code, which is exchanged for an access token and refresh token.
▪ Error Handling and Edge Cases: The application handles potential errors and
edge cases that may arise during interactions with the Spotify API. This
includes scenarios such as invalid access tokens, expired tokens, rate limiting,
and network errors. Error handling mechanisms ensure that the application
provides a smooth and reliable user experience even in the face of API-related
issues.
30
Scalability:
4.5.6 Appendices
Include any additional information relevant to the software requirements, such as use
case diagrams, data flow diagrams, or mockups.
31
4.6.1 Iterative Development: The project can be broken down into smaller increments or
iterations, allowing for continuous improvement and feedback throughout the development
process. Features can be implemented incrementally, with regular demonstrations to
stakeholders for feedback and validation.
4.6.4 Customer-Centric Focus: Agile places a strong emphasis on delivering value to the
customer. In this project, the customer-centric focus means prioritizing features and
functionalities that align with user needs and preferences, ensuring a positive user experience.
4.6.6 Sprint Planning: The project team conducts regular sprint planning meetings to
prioritize tasks and set goals for each iteration. This ensures that development efforts are
focused on delivering the most valuable features incrementally.
4.6.7 Daily Stand-ups: Daily stand-up meetings are held to provide a forum for team
members to discuss progress, identify any impediments, and coordinate their efforts. These
short, focused meetings help maintain alignment and address any issues promptly.
4.6.8 Iterative Feedback: Agile encourages continuous feedback loops, both from
stakeholders and end-users. Regular demos and reviews allow stakeholders to provide
feedback on the product's features and functionality, facilitating early course correction and
improvement.
32
4.6.9 Empowered Teams: Agile principles promote self-organizing, empowered teams that
take ownership of their work. Team members have the autonomy to make decisions and
adapt to changing requirements, fostering a sense of accountability and commitment to
project success.
4.6.11 Adaptive Planning: Agile methodologies recognize that requirements and priorities
may evolve over time. The project plan remains flexible, allowing for adjustments based on
feedback, changes in market conditions, or emerging opportunities.
33
4. SYSTEM DESIGN AND SPECIFICATIONS
The system design and specifications for this project outline the architecture, components,
and functionality of the collaborative music playback system. Here's an overview:
❖ Architecture:
The system follows a client-server architecture, where the server hosts the backend
logic and data storage, while the client interacts with the user through a web-based
interface.
Backend components include Django framework for server-side logic, Spotify API
integration for music playback functionality, and a PostgreSQL database for storing
user data and room information.
Frontend components utilize React.js for building interactive user interfaces and
managing state.
❖ Components:
Backend Components:
• PostgreSQL database for storing user profiles, room details, playback history, and
voting data.
Frontend Components:
• React.js for building modular UI components, managing state, and handling user
interactions.
• Material-UI library for designing responsive and visually appealing user interfaces.
• React Router for client-side routing to navigate between different views within the
application.
34
❖ Functionality:
User Authentication: Users can log in to the system using their Spotify accounts to
access the collaborative music playback features.
Room Management: Hosts can create a room and generate a unique code that other
users can use to join the room. Hosts can also set room preferences such as playback
control permissions and voting requirements.
Music Playback: Users can play, pause, skip tracks, and adjust playback volume
within the room. Playback control permissions are determined by the host's settings.
Voting System: Users can vote to skip tracks, and tracks are skipped when the
required number of votes is reached.
Real-time Updates: Hosts can update playback control settings and voting
requirements in real-time, reflecting changes immediately for all users in the room.
❖ Specifications:
System supports concurrent user sessions with efficient handling of authentication and
session management.
Integration with Spotify API ensures seamless access to music catalogs, playback
control, and user authentication.
Data storage and retrieval operations are optimized for performance and scalability,
ensuring smooth operation even under high user loads.
35
❖ SOFTWARE DESIGN
Modularity and partitioning: Software is designed such that, each system should
consists of hierarchy of modules and serve to partition into separate function.
Shared use: Avoid duplication by allowing a single module be called by other that
need the function it provides.
❖ MODULE DESIGN
Home Module
Home Module:
36
Handles the OAuth flow for obtaining user authorization.
Retrieves user profile information and access tokens for Spotify API interaction.
Displays information about the currently playing song, including the title, artist,
album cover, playback progress, and voting details.
Users can interact with the music player through buttons such as play, pause, and
skip. These buttons trigger actions to control the playback accordingly.
It also displays the number of votes each song has received for skipping
37
❖ DATABASE DESIGN
38
❖ INPUT/OUTPUT DESIGN
Input Design
The input design for the collaborative music playback system involves defining how
users interact with the application to input commands, preferences, and data. Here's an
overview of the input design:
The UI includes various input elements such as text fields, buttons, dropdowns,
and sliders.
Users interact with these elements to perform actions like logging in, creating
rooms, joining rooms, controlling playback, and voting on tracks.
o Authentication Inputs:
Input fields for users to enter their login credentials (username/email and
password) during the authentication process.
Text fields for specifying room preferences such as room name, playback
control permissions, and voting rules.
Text field for entering the room code when joining an existing room.
39
o Playback Control Inputs:
o Voting Inputs:
Output Design
The output design of the project involves presenting information and feedback to
users based on their interactions with the system. Here's an overview of the output
design elements in our collaborative music playback system:
User Interface: The system provides a user-friendly interface using React and
Material-UI components. It includes screens for different functionalities like
home, room creation, room joining, music playback, and settings.
Room Information: Upon joining a room or creating a new one, users see
relevant information such as the room code, current song details, playback
controls, and voting status.
Music Playback: The output design includes a music player interface with
controls for play, pause, and skip. It also displays the current song's title, artist,
album cover, playback progress, and voting details.
40
5.1 DATA MODEL(LIKE DFD)
A Data Flow Diagram (DFD) is a traditional visual representation of the information flows
within a system. A neat and clear DFD can depict the right amount of the system requirement
graphically. It can be manual, automated, or a combination of both.
It shows how data enters and leaves the system, what changes the information, and where
data is stored.
The objective of a DFD is to show the scope and boundaries of a system as a whole. It may
be used as a communication tool between a system analyst and any person who plays a part
in the order that acts as a starting point for redesigning a system. The DFD is also called as a
data flow graph or bubble chart.
41
➢ Source or Destination of Data: External sources or destinations of data, which
may be people or organizations or other entities.
It is also known as a context diagram. It’s designed to be an abstraction view, showing the
system as a single process with its relationship to external entities. It represents the entire
system as a single bubble with input and output data indicated by incoming/outgoing
arrows.
42
5.1.2 Level 1 DFD
This level provides a more detailed view of the system by breaking down the major
processes identified in the level 0 DFD into sub-processes. Each sub-process is depicted as
a separate process on the level 1 DFD. The data flows and data stores associated with each
sub-process are also shown.
In 1-level DFD, the context diagram is decomposed into multiple bubbles/processes. In this
level, we highlight the main functions of the system and breakdown the high-level process
of 0-level DFD into subprocesses.
43
5.2 ENTITY RELATIONSHIP MODEL
ER model stands for an Entity-Relationship model. It is a high-level data model. This model
is used to define the data elements and relationship for a specified system.
It develops a conceptual design for the database. It also develops a very simple and easy to
design view of data.
44
5.4 CLASS DIAGRAM
Class diagrams are a type of UML (Unified Modeling Language) diagram used in software
engineering to visually represent the structure and relationships of classes within a system
i.e. used to construct and visualize object-oriented systems.
45
Class diagrams provide a high-level overview of a system’s design, helping to
communicate and document the structure of the software. They are a fundamental tool in
object-oriented design and play a crucial role in the software development lifecycle.
46
5.5 STATE DIAGRAM/SEQUENCE DIAGRAM
A sequence diagram shows process interactions arranged in time sequence. This diagram
depicts the processes and objects involved and the sequence of messages exchanged as
needed to carry out the functionality.
47
5. SOURCE CODE
6.1 HTML template that provides structure to the application
<!DOCTYPE html>
<html>
<head>
<title>Tune Troop</title>
{% load static %}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<link
rel="stylesheet"
href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700&display=swap"
/>
/>
</head>
<body>
<div id="gradient">
<div id="main">
<div id="app"></div>
</div>
</div>
</body>
</html>
48
6.2 CSS for styling
html,
body {
height: 100%;
margin: 0;
padding: 0;
#main {
position: fixed;
width: 100%;
height: 100%;
left: 0;
top: 0;
#app {
width: 100%;
height: 100%;
.center {
position: absolute;
top: 50%;
left: 50%;
#gradient {
49
width: 100%;
height: 800px;
padding: 0px;
margin: 0px;
[62,35,255],
[60,255,60],
[255,35,98],
[45,175,230],
[255,0,255],
[255,128,0]);
var step = 0;
//transition speed
function updateGradient()
50
{
if ( $===undefined ) return;
$('#gradient').css({
step += gradientSpeed;
if ( step >= 1 )
step %= 1;
51
colorIndices[0] = colorIndices[1];
colorIndices[2] = colorIndices[3];
setInterval(updateGradient,10);
import string
import random
def generate_unique_code():
length = 6
while True:
if Room.objects.filter(code=code).count() == 0:
break
return code
52
class Room(models.Model):
code = models.CharField(
created_at = models.DateTimeField(auto_now_add=True)
6.5 Creation of serializers for the ‘Room’ model in the Django REST
Framework
from rest_framework import serializers
class RoomSerializer(serializers.ModelSerializer):
class Meta:
model = Room
'votes_to_skip', 'created_at')
class CreateRoomSerializer(serializers.ModelSerializer):
class Meta:
model = Room
class UpdateRoomSerializer(serializers.ModelSerializer):
code = serializers.CharField(validators=[])
53
class Meta:
model = Room
fields = ('guest_can_pause', 'votes_to_skip', 'code')
class RoomView(generics.ListAPIView):
queryset = Room.objects.all()
serializer_class = RoomSerializer
class GetRoom(APIView):
serializer_class = RoomSerializer
lookup_url_kwarg = 'code'
code = request.GET.get(self.lookup_url_kwarg)
if code != None:
room = Room.objects.filter(code=code)
if len(room) > 0:
data = RoomSerializer(room[0]).data
54
return Response(data, status=status.HTTP_200_OK)
class JoinRoom(APIView):
lookup_url_kwarg = 'code'
if not self.request.session.exists(self.request.session.session_key):
self.request.session.create()
code = request.data.get(self.lookup_url_kwarg)
if code != None:
room_result = Room.objects.filter(code=code)
if len(room_result) > 0:
room = room_result[0]
self.request.session['room_code'] = code
return Response({'Bad Request': 'Invalid post data, did not find a code key'},
status=status.HTTP_400_BAD_REQUEST)
class CreateRoomView(APIView):
serializer_class = CreateRoomSerializer
55
def post(self, request, format=None):
if not self.request.session.exists(self.request.session.session_key):
self.request.session.create()
serializer = self.serializer_class(data=request.data)
if serializer.is_valid():
guest_can_pause = serializer.data.get('guest_can_pause')
votes_to_skip = serializer.data.get('votes_to_skip')
host = self.request.session.session_key
queryset = Room.objects.filter(host=host)
if queryset.exists():
room = queryset[0]
room.guest_can_pause = guest_can_pause
room.votes_to_skip = votes_to_skip
room.save(update_fields=['guest_can_pause', 'votes_to_skip'])
self.request.session['room_code'] = room.code
else:
votes_to_skip=votes_to_skip)
room.save()
self.request.session['room_code'] = room.code
class UserInRoom(APIView):
56
def get(self, request, format=None):
if not self.request.session.exists(self.request.session.session_key):
self.request.session.create()
data = {
'code': self.request.session.get('room_code')
class LeaveRoom(APIView):
if 'room_code' in self.request.session:
self.request.session.pop('room_code')
host_id = self.request.session.session_key
room_results = Room.objects.filter(host=host_id)
if len(room_results) > 0:
room = room_results[0]
room.delete()
class UpdateRoom(APIView):
serializer_class = UpdateRoomSerializer
if not self.request.session.exists(self.request.session.session_key):
self.request.session.create()
serializer = self.serializer_class(data=request.data)
57
if serializer.is_valid():
guest_can_pause = serializer.data.get('guest_can_pause')
votes_to_skip = serializer.data.get('votes_to_skip')
code = serializer.data.get('code')
queryset = Room.objects.filter(code=code)
if not queryset.exists():
room = queryset[0]
user_id = self.request.session.session_key
if room.host != user_id:
room.guest_can_pause = guest_can_pause
room.votes_to_skip = votes_to_skip
room.save(update_fields=['guest_can_pause', 'votes_to_skip'])
58
urlpatterns = [
path('room', RoomView.as_view()),
path('create-room', CreateRoomView.as_view()),
path('get-room', GetRoom.as_view()),
path('join-room', JoinRoom.as_view()),
path('user-in-room', UserInRoom.as_view()),
path('leave-room', LeaveRoom.as_view()),
path('update-room', UpdateRoom.as_view())
constructor(props) {
super(props);
render() {
return (
<div className="center">
<HomePage />
</div>
);
59
const appDiv = document.getElementById("app");
import { BrowserRouter as Router, Routes, Route, Link, Redirect, Navigate } from 'react-
router-dom';
constructor(props){
super(props);
this.state={
roomCode: null,
};
this.clearRoomCode=this.clearRoomCode.bind(this);
async componentDidMount(){
fetch('/api/user-in-room')
.then((response)=>response.json()).
then((data)=>{
this.setState({
roomCode:data.code,
});
});
60
}
renderHomePage(){
if(this.state.roomCode){
return(
);
}else{
return(
Tune Troop
</Typography>
</Grid>
Create a Room
</Button>
Join a Room
</Button>
</ButtonGroup>
</Grid>
</Grid>
);
61
clearRoomCode(){
this.setState({
roomCode:null,
});
render(){
return (<Router>
<Routes>
/>
</Route>
</Routes>
</Router>);
62
import {FormHelperText} from "@mui/material";
function CreateRoomPage(props){
const navigate=useNavigate();
const[guestCanPause,setguestCanPause]=useState(props.guestCanPause);
const[votesToSkip,setgvotesToSkip]=useState(props.votesToSkip);
const[errorMsg,setErrorMsg]=useState("");
const[successMsg,setSuccessMsg]=useState("");
const handleVotesChange=()=>{
setgvotesToSkip(event.target.value);
};
const handleGuestCanPauseChange=()=>{
setguestCanPause(event.target.value==="true"?true:false);
};
const handleRoomButtonPressed=()=>{
const requestOptions = {
method: 'POST',
63
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({
votes_to_skip:votesToSkip,
guest_can_pause:guestCanPause,
}),
};
fetch('/api/create-room', requestOptions)
.then((response)=>response.json())
};
const handleUpdateButtonPressed=()=>{
const requestOptions = {
method: 'PATCH',
body: JSON.stringify({
votes_to_skip:votesToSkip,
guest_can_pause:guestCanPause,
code:props.roomCode,
}),
};
fetch('/api/update-room', requestOptions)
.then((response)=>{
if(response.ok){
}else{
props.updateCallback();
64
});
};
const renderCreateButtons=()=>{
return(
</Grid>
</Grid>
</Grid>
);
};
const renderUpdateButtons=()=>{
return(
</Grid>
</Grid>
);
};
65
const title=props.update? "Update Room" : "Create a Room";
return (
{successMsg!=""?(
<Alert
severity="success"
onClose={()=>{
setSuccessMsg("");
}}>
{successMsg}
</Alert>
):(
<Alert
severity="error"
onClose={()=>{
setErrorMsg("");
}}>
{errorMsg}
</Alert>
)}
</Collapse>
</Grid>
{title}
</Typography>
66
</Grid>
<FormControl component="fieldset">
<FormHelperText component="div">
</FormHelperText>
labelPlacement="bottom"></FormControlLabel>
</RadioGroup>
</FormControl>
</Grid>
<FormControl>
inputProps={{min:1, style:{textAlign:"center"},}}></TextField>
<FormHelperText component="div">
<div align="center">
</div>
</FormHelperText>
</FormControl>
67
</Grid>
{props.update?renderUpdateButtons(): renderCreateButtons()}
</Grid>
);
CreateRoomPage.defaultProps={
votesToSkip:2,
guestCanPause:true,
update: false,
roomCode:null,
updateCallback:()=>{},
};
const navigate=useNavigate();
const[roomCode, setroomCode]=useState('');
const[errorMsg,seterrorMsg]=useState('');
const[error,seterror]=useState(false);
const handleTextFieldChange=()=>{
68
setroomCode(event.target.value);
};
const roomButtonPressed=()=>{
const requestOptions={
method: "POST",
headers:{"Content-Type": "application/json"},
body:JSON.stringify({
code:roomCode,
}),
};
fetch("/api/join-room",requestOptions).
then((response)=>{
if(response.ok){
navigate("/room/"+ roomCode)
}else{
seterror(true);
})
.catch((error)=>{
console.log(error);
});
};
return(
Join a Room
69
</Typography>
</Grid>
<TextField
error={error}
label="Code"
value={roomCode}
helperText={errorMsg}
variant='outlined'
onChange={handleTextFieldChange}>
</TextField>
</Grid>
<Button
variant='contained'
color='primary'
onClick={roomButtonPressed}>
Enter Room
</Button>
</Grid>
<Button variant='contained'
Back
</Button>
</Grid>
</Grid>
70
);
function Room(props){
const navigate=useNavigate();
const{roomCode}=useParams()
const initialState={
votesToSkip:2,
guestCanPause:false,
isHost:false,
showSettings: false,
spotifyAuthenticated: false,
song:{},
}
const[roomData, setRoomData]=useState(initialState)
useEffect(() => {
getRoomDetails();
return ()=>clearInterval(interval);
},[roomCode]);
71
const getRoomDetails = () => {
.then((response) => {
if (!response.ok) {
props.clearRoomCodeCallback();
navigate("/");
return response.json();
})
.then((data) => {
setRoomData(prevState=>({
...prevState,
votesToSkip: data.votes_to_skip,
guestCanPause: data.guest_can_pause,
isHost: data.is_host
}));
if(data.is_host){
authenticateSpotify();
});
};
const authenticateSpotify=()=>{
fetch("/spotify/is-authenticated")
.then((data) => {
console.log(data.status);
if (!data.status) {
72
fetch("/spotify/get-auth-url")
.then((data) => {
window.location.replace(data.url);
});
});
};
fetch('/spotify/current-song')
.then((response) => {
if (!response.ok) {
return {};
} else {
return response.json();
})
.then((data) => {
console.log(data);
});
};
const leaveButtonPressed=()=>{
const requestOptions={
method: "POST",
headers:{"Content-Type": "application/json"},
};
73
fetch('/api/leave-room',requestOptions).
then((response)=>{
props.clearRoomCodeCallback();
navigate('/');
});
};
const updateShowSettings=(value)=>{
setRoomData({
...roomData,
showSettings:value,
});
};
const renderSettings=()=>{
return(
<Grid container spacing={1}>
<CreateRoomPage
update={true}
votesToSkip={roomData.votesToSkip}
guestCanPause={roomData.guestCanPause}
roomCode={roomCode}
updateCallback={getRoomDetails}
getRoomDetails={getRoomDetails}
/>
</Grid>
<Button
74
variant='contained'
color='secondary'
onClick={()=>updateShowSettings(false)}
>
Close
</Button>
</Grid>
</Grid>
);
};
const renderSettingsButton=()=>{
return(
Settings
</Button>
</Grid>
);
};
return roomData.showSettings?(
renderSettings()
):(
75
Code:{roomCode}
</Typography>
</Grid>
<MusicPlayer {...roomData.song}/>
{roomData.isHost?renderSettingsButton():null}
Leave Room
</Button>
</Grid>
</Grid>
Grid,
Typography,
Card,
IconButton,
LinearProgress,
} from '@mui/material';
76
const requestOptions = {
method: "POST",
headers: { "Content-Type": "application/json" },
};
fetch("/spotify/skip", requestOptions);
};
const requestOptions = {
method: "PUT",
headers: { "Content-Type": "application/json" },
};
fetch("/spotify/pause", requestOptions);
};
const requestOptions = {
method: "PUT",
headers: { "Content-Type": "application/json" },
};
fetch("/spotify/play", requestOptions);
};
return (
<Card>
</Grid>
77
<Grid item align="center" xs={8}>
{props.title}
</Typography>
{props.artist}
</Typography>
<div>
{props.is_playing ? <Pause></Pause> :
<PlayArrowRounded></PlayArrowRounded>}
</IconButton>
<IconButton onClick={()=>skipSong()}>
{props.votes}/{" "}{props.votes_required}
<SkipNext></SkipNext>
</IconButton>
</div>
</Grid>
</Grid>
</Card>
);
};
78
6.14 Django model for storing Spotify authentication tokens and user votes
from django.db import models
class SpotifyToken(models.Model):
created_at = models.DateTimeField(auto_now_add=True)
refresh_token = models.CharField(max_length=150)
access_token = models.CharField(max_length=150)
expires_in = models.DateTimeField()
token_type = models.CharField(max_length=50)
class Vote(models.Model):
created_at = models.DateTimeField(auto_now_add=True)
song_id = models.CharField(max_length=50)
REDIRECT_URI = "http://127.0.0.1:8000/spotify/redirect"
79
from rest_framework.response import Response
class AuthURL(APIView):
'scope': scopes,
'response_type': 'code',
'redirect_uri': REDIRECT_URI,
'client_id': CLIENT_ID
}).prepare().url
code = request.GET.get('code')
error = request.GET.get('error')
'grant_type': 'authorization_code',
'code': code,
'redirect_uri': REDIRECT_URI,
'client_id': CLIENT_ID,
'client_secret': CLIENT_SECRET
80
}).json()
access_token = response.get('access_token')
token_type = response.get('token_type')
refresh_token = response.get('refresh_token')
expires_in = response.get('expires_in')
error = response.get('error')
if not request.session.exists(request.session.session_key):
request.session.create()
update_or_create_user_tokens(
return redirect('frontend:')
class IsAuthenticated(APIView):
is_authenticated = is_spotify_authenticated(
self.request.session.session_key)
class CurrentSong(APIView):
room_code = self.request.session.get('room_code')
room = Room.objects.filter(code=room_code)
if room.exists():
room = room[0]
else:
81
return Response({}, status=status.HTTP_404_NOT_FOUND)
host = room.host
endpoint = "player/currently-playing"
item = response.get('item')
duration = item.get('duration_ms')
progress = response.get('progress_ms')
album_cover = item.get('album').get('images')[0].get('url')
is_playing = response.get('is_playing')
song_id = item.get('id')
artist_string = ""
if i > 0:
name = artist.get('name')
artist_string += name
song = {
'title': item.get('name'),
'artist': artist_string,
'duration': duration,
'time': progress,
82
'image_url': album_cover,
'is_playing': is_playing,
'votes': votes,
'votes_required': room.votes_to_skip,
'id': song_id
self.update_room_song(room, song_id)
current_song = room.current_song
if current_song != song_id:
room.current_song = song_id
room.save(update_fields=['current_song'])
votes = Vote.objects.filter(room=room).delete()
class PauseSong(APIView):
room_code = self.request.session.get('room_code')
room = Room.objects.filter(code=room_code)[0]
pause_song(room.host)
83
class PlaySong(APIView):
room_code = self.request.session.get('room_code')
room = Room.objects.filter(code=room_code)[0]
play_song(room.host)
return Response({}, status=status.HTTP_204_NO_CONTENT)
class SkipSong(APIView):
room_code = self.request.session.get('room_code')
room = Room.objects.filter(code=room_code)[0]
votes_needed = room.votes_to_skip
votes.delete()
skip_song(room.host)
else:
vote = Vote(user=self.request.session.session_key,
room=room, song_id=room.current_song)
vote.save()
84
6.17 To handle Spotify authentication and integration using Spotify API
from .models import SpotifyToken
BASE_URL = "https://api.spotify.com/v1/me/"
def get_user_tokens(session_id):
user_tokens = SpotifyToken.objects.filter(user=session_id)
if user_tokens.exists():
return user_tokens[0]
else:
return None
tokens = get_user_tokens(session_id)
if tokens:
tokens.access_token = access_token
tokens.refresh_token = refresh_token
tokens.expires_in = expires_in
tokens.token_type = token_type
tokens.save(update_fields=['access_token',
'refresh_token', 'expires_in', 'token_type'])
85
else:
refresh_token=refresh_token, token_type=token_type,
expires_in=expires_in)
tokens.save()
def is_spotify_authenticated(session_id):
tokens = get_user_tokens(session_id)
if tokens:
expiry = tokens.expires_in
refresh_spotify_token(session_id)
return True
return False
def refresh_spotify_token(session_id):
refresh_token = get_user_tokens(session_id).refresh_token
'grant_type': 'refresh_token',
'refresh_token': refresh_token,
'client_id': CLIENT_ID,
'client_secret': CLIENT_SECRET
}).json()
access_token = response.get('access_token')
token_type = response.get('token_type')
86
expires_in = response.get('expires_in')
update_or_create_user_tokens(
tokens = get_user_tokens(session_id)
if post_:
if put_:
try:
return response.json()
except:
return {'Error': 'Issue with request'}
def play_song(session_id):
def pause_song(session_id):
def skip_song(session_id):
87
6.18 URL patterns for the API views
from django.urls import path
urlpatterns = [
path('get-auth-url', AuthURL.as_view()),
path('redirect', spotify_callback),
path('is-authenticated', IsAuthenticated.as_view()),
path('current-song', CurrentSong.as_view()),
path('pause', PauseSong.as_view()),
path('play', PlaySong.as_view()),
path('skip', SkipSong.as_view())
6.19 URL pattern to include URLS from different parts of the application
from django.contrib import admin
urlpatterns = [
path('admin/', admin.site.urls),
path('api/', include('api.urls')),
path('', include('frontend.urls')),
path('spotify/', include('spotify.urls'))
88
6. SCREENSHOT
89
7.3 SPOTIFY ACCOUNT LOGIN PAGE
90
7.5 UPDATE ROOM PAGE
91
7.5 MUSIC PLAYER PAGE FOR GUEST
92
7. TESTING
Software testing can be stated as the process of verifying and validating whether a software
or application is bug-free, meets the technical requirements as guided by its design and
development, and meets the user requirements effectively and efficiently by handling all
the exceptional and boundary cases.
The purpose of software testing is to identify the errors, faults, or missing requirements in
contrast to actual requirements. It mainly aims at measuring the specification, functionality,
and performance of a software program or application.
Validation: Ensure that the software meets the specified requirements and fulfills its
intended purpose effectively and accurately.
Verification: Confirm that the software conforms to its design specifications and
standards, ensuring consistency and reliability in its behavior.
Identification of Defects: Detect and identify any defects, bugs, or errors in the
software early in the development process to prevent them from impacting the end-
users or causing issues in production.
Quality Assurance: Ensure that the software meets predefined quality standards,
including functionality, performance, security, usability, and maintainability.
Risk Mitigation: Identify and mitigate potential risks associated with the software,
such as security vulnerabilities, performance bottlenecks, and usability issues, to
minimize their impact on the end-users and the organization.
93
Compliance: Ensure that the software complies with relevant laws, regulations,
standards, and industry best practices, such as accessibility standards, data privacy
regulations, and security guidelines.
Cost Reduction: Identify and eliminate defects and inefficiencies early in the
development lifecycle to reduce the overall cost of software development,
maintenance, and support.
System Testing: Test the entire system as a whole to verify that it meets the specified
requirements and functions correctly in its intended environment.
Acceptance Testing: Test the software from the end-user's perspective to determine if
it meets their needs and expectations.
Regression Testing: Test previously implemented features to ensure they still function
correctly after new changes or updates are made.
Security Testing: Identify and mitigate potential security vulnerabilities and threats to
protect the software and its users' data.
94
Usability Testing: Evaluate the software's user interface and overall user experience to
ensure it is intuitive, easy to use, and meets the users' needs.
Risk-Based Testing: Prioritize testing efforts based on the criticality and impact of
identified risks to ensure the most important areas are thoroughly tested.
Agile Testing: Integrate testing activities into the Agile development process, with
frequent iterations and continuous feedback loops to ensure rapid and reliable
delivery of software increments.
Shift-Left Testing: Begin testing activities early in the software development lifecycle
to detect and address defects as soon as possible, reducing the cost and effort of
fixing them later.
Black Box and White Box Testing: Employ a combination of black box testing
(testing based on external behavior) and white box testing (testing based on internal
code structure) to ensure comprehensive test coverage.
Scope: Define the scope of testing, including the features, functionalities, and
components to be tested.
Test Environment: Specify the test environment, including hardware, software, tools,
and configurations required for testing.
95